fix(svelte-store): use $state.raw in useSelector to prevent proxy equality mismatch #334
main fromrefs/pull/334/head·opened 🎯 Changes#
Fixes #322
$state() wraps object values in a Svelte Proxy. When selector(s) returns the same
raw object reference, === comparison with the Proxy always fails — triggering
state_proxy_equality_mismatch warnings and unnecessary re-renders even when the
selected value hasn't changed.
Existing tests only covered primitive selectors, which are not Proxy-wrapped. A new test with an object selector reproduces the issue and verifies the fix.
Switching to $state.raw() is safe since useSelector only ever reassigns slice,
never mutates its properties.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm test:pr.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Summary by CodeRabbit#
- Bug Fixes
- Fixed
useSelectorselector equality handling to preventstate_proxy_equality_mismatchwarnings and unnecessary re-renders when the selected value is effectively unchanged.
- Fixed
- Tests
- Added and expanded Svelte tests covering proxy equality and selector memoization, including scenarios where unrelated store fields update.
- Chores
- Added a release metadata entry documenting the patch fix.
- 1
🧹 Nitpick comments (1)
packages/svelte-store/src/useSelector.svelte.ts (1)
38-38: ⚡ Quick winConsider adding an inline comment to explain the use of
$state.raw().Future maintainers might wonder why
$state.raw()is used instead of$state(). A brief comment explaining that raw prevents proxy wrapping and ensures correct equality checks would improve maintainability.📝 Suggested comment
const compare = options.compare ?? defaultCompare - let slice = $state.raw(selector(source.get())) + // Use $state.raw() to prevent Svelte Proxy wrapping, ensuring === comparison + // with raw selector output works correctly (prevents state_proxy_equality_mismatch) + let slice = $state.raw(selector(source.get()))🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/svelte-store/src/useSelector.svelte.ts` at line 38, Add a brief inline comment above the expression using $state.raw(selector(source.get())) explaining why .raw() is used (to bypass proxy wrapping so selector equality checks compare plain values rather than proxies), e.g., reference the $state.raw call and the selector/source.get usage in the same line so maintainers see that raw prevents proxy-wrapped results from breaking equality checks in the slice variable assignment.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Nitpick comments: In `@packages/svelte-store/src/useSelector.svelte.ts`: - Line 38: Add a brief inline comment above the expression using $state.raw(selector(source.get())) explaining why .raw() is used (to bypass proxy wrapping so selector equality checks compare plain values rather than proxies), e.g., reference the $state.raw call and the selector/source.get usage in the same line so maintainers see that raw prevents proxy-wrapped results from breaking equality checks in the slice variable assignment.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
da0d8182-7e6e-40ae-aa67-b03109e64bfb📥 Commits
Reviewing files that changed from the base of the PR and between 86251e5d6b59cca9b965b9306557ab693706bf69 and 050f9b99fcbec75ce2240e0b489e107cd27e2291.
📒 Files selected for processing (4)
.changeset/fix-svelte-store-proxy-equality.mdpackages/svelte-store/src/useSelector.svelte.tspackages/svelte-store/tests/ProxyEquality.test.sveltepackages/svelte-store/tests/index.test.ts
Independent confirmation from another downstream consumer, plus a measurement of what this actually costs — in case it helps get the PR over the line.
Hit in a SvelteKit/Tauri app on
@tanstack/svelte-table@9.0.0-beta.52(souseSelectorviacreateTable),@tanstack/svelte-store@0.12.0, Svelte 5.56.4. Same path as #322:defaultCompare→ Svelte's instrumentedstrict_equals→ one warning per store notification.It isn't only a warning#
Isolated against
@tanstack/svelte-storedirectly, no table involved: an atom whose selected slice keeps one identity for the whole run while an unrelated field changes — the case a selector exists to memoize. Three updates, each flushed individually (a synchronous burst coalesces into a single effect run and hides the per-update cost).Arm Slice compareEffect runs Distinct .currentidentitiesA object default ( ===)4 4 B object (a, b) => a.id === b.id1 1 C string default ( ===)1 1 A correct selector reads 1 / 1 in every row. B shows the compare is the causal lever; C shows the proxying is the cause — primitives are never proxied — rather than the store or the subscription.
The reason it's a re-render and not just a false branch:
compare(proxy, raw)is false →slice = data→ Svelte'sset()callsproxy(data), which mints a brand-new Proxy every time (there is no per-target cache) →source.equals(new_proxy)is false → the source version bumps and every dependent re-runs. SouseSelectorcurrently notifies on every store emission whatever the selector returns.Small supporting detail:
strict_equalswarns only when(a === b) !== (get_proxied_value(a) === get_proxied_value(b)), so the warning is itself an assertion that the two operands are the same object and===is wrong about it.The harness (Svelte component + assertions)
<script lang="ts"> import { createAtom, useSelector } from '@tanstack/svelte-store'; let { mode = 'default', onapi } = $props(); // Only `tick` ever changes; the selected slice keeps one identity. const STABLE = { id: 'stable', rows: ['a', 'b'] }; const atom = createAtom({ slice: STABLE, label: 'constant', tick: 0 }); const selected = mode === 'primitive' ? useSelector(atom, (s) => s.label) : mode === 'keyed-compare' ? useSelector(atom, (s) => s.slice, { compare: (a, b) => a?.id === b?.id }) : useSelector(atom, (s) => s.slice); // Plain locals: the measurement must not join the reactivity it measures. let effectRuns = 0; const identities = new Set(); $effect(() => { identities.add(selected.current); effectRuns += 1; }); onapi({ bump: () => atom.set((prev) => ({ ...prev, tick: prev.tick + 1 })), report: () => ({ effectRuns, distinctIdentities: identities.size }), }); </script>// Each update flushed on its own, or Svelte coalesces the burst into one run. for (let i = 0; i < 3; i++) { api.bump(); flushSync(); } expect(api.report()).toEqual({ effectRuns: 1, distinctIdentities: 1 }); // fails: 4 / 4On the safety of
$state.raw#One behavioural change worth naming explicitly, since it's the thing that could hold up a merge:
.currentstops being deeply reactive, so anyone mutating the selected object in place (selected.current.foo = 1) and watching the UI update loses that.That path looks like a bug being relied on rather than a feature — the object belongs to the store, and writing through the proxy writes into store-owned state behind the store's back. Replacement-based updates, which are the store's actual contract, are unaffected:
sliceis only ever reassigned, never mutated, exactly as the PR description says.Blast radius#
The whole public surface routes through
useSelector—useAtom,useStoreand_useStoreall delegate to it — so this is object-slice behaviour for the package generally, not one entry point. Downstream it reaches@tanstack/svelte-tablev9 (itscreateTablecallsuseSelector(table.store, selector)with nocompare, so consumers have no seam to work around it) and@tanstack/form(TanStack/form#2256).Still present on the newest published bits:
svelte-table@9.0.0-beta.56callsuseSelectorunchanged,svelte-store@0.12.0is the latest release, andmainstill haslet slice = $state(...).$state.is— the obvious consumer-side proxy-aware comparison — has been removed from Svelte, so there's no clean workaround outside the library.Happy to port this harness into
packages/svelte-store/testsalongside the test already in this PR if that would help.Happy to port this harness into
packages/svelte-store/testsalongside the test already in this PR if that would help.Thanks @jizc for the thorough analysis and independent confirmation — the measurement showing this causes actual re-renders rather than just warnings makes the case much stronger, and the breakdown of why reassigning slice mints a fresh proxy on every set() matches exactly what I saw.
Yes please, that would help — go ahead and port it. You can open a PR against the branch this one is from (seongwon030:fix/svelte-store-use-selector-proxy-equality) and I'll merge it in, so it lands here with your commits intact.
@KevinVandy / @crutchcorn — could one of you approve the workflow run on this PR?
This still reproduces on current
main(c1a40d4) and in 0.12.2.useSelector.svelte.ts#L38still holds the slice in$state.I wrote a regression test separately from the ones here (commit): select an object, change an unrelated field, count effect runs. It fails on
mainwithstate_proxy_equality_mismatch, and passes on this branch (dd5da7b) along with the rest of the suite (18/18).Also, the fix has since been opened a second time, as #364 for #363, which is a second report of #322. Merging this would cover both issues, and #364 could be closed.
Hey, apologies, but I prefer the formatting of this PR:
https://github.com/TanStack/store/pull/364
We'll get that merged right now though
crutchcorn(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
f6c66388-5271-4883-9989-0416d6d10215📥 Commits
Reviewing files that changed from the base of the PR and between 637447a0222861a7f57d9426b271785acea6f1fe and dd5da7b12b394525264e815fbb8db729a493ac7b.
📒 Files selected for processing (2)
packages/svelte-store/tests/SelectorMemoization.test.sveltepackages/svelte-store/tests/index.test.ts📝 Walkthrough
Walkthrough#
This PR changes
useSelectorto store its selected slice with$state.raw(), preventing proxy-wrapped equality comparisons. It adds a changeset and tests for stable references, memoization, render counts, and warning suppression.Changes#
useSelector Svelte proxy equality fix
packages/svelte-store/src/useSelector.svelte.ts,.changeset/fix-svelte-store-proxy-equality.md$state.raw(selector(source.get()))and documents the patch release.packages/svelte-store/tests/ProxyEquality.test.svelte,packages/svelte-store/tests/SelectorMemoization.test.svelte,packages/svelte-store/tests/index.test.tsstate_proxy_equality_mismatchwarnings.Estimated code review effort: 2 (Simple) | ~10 minutes
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
#322by switching useSelector to $state.raw and adding regression tests for the proxy equality warning.✨ Finishing Touches
🧪 Generate unit tests (beta)
Warning
There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.
🔧 ESLint
ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share