Skip to content
Source
Sign inSign up
TanStack/store

fix(svelte-store): use $state.raw in useSelector to prevent proxy equality mismatch #334

Closedseongwon030(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/334/headopened

🎯 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 useSelector selector equality handling to prevent state_proxy_equality_mismatch warnings and unnecessary re-renders when the selected value is effectively unchanged.
  • 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. Review Change Stack

      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.svelte
      • packages/svelte-store/tests/index.test.ts

      📝 Walkthrough

      Walkthrough

      This PR changes useSelector to 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

      Layer / File(s)Summary
      useSelector raw slice fix and changeset
      packages/svelte-store/src/useSelector.svelte.ts, .changeset/fix-svelte-store-proxy-equality.md
      Initializes the selector slice with $state.raw(selector(source.get())) and documents the patch release.
      Equality and memoization regression coverage
      packages/svelte-store/tests/ProxyEquality.test.svelte, packages/svelte-store/tests/SelectorMemoization.test.svelte, packages/svelte-store/tests/index.test.ts
      Adds component and integration tests covering ignored updates, stable object identity, selector memoization, render counts, keyed and primitive selectors, and suppression of state_proxy_equality_mismatch warnings.

      Estimated code review effort: 2 (Simple) | ~10 minutes

      🚥 Pre-merge checks | ✅ 5
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title is concise and accurately describes the main code change and its purpose.
      Description check✅ PassedThe description follows the required template and fills the Changes, Checklist, and Release Impact sections.
      Linked Issues check✅ PassedThe PR fixes #322 by switching useSelector to $state.raw and adding regression tests for the proxy equality warning.
      Out of Scope Changes check✅ PassedAll code and changeset updates are directly related to the selector proxy-equality fix and its tests.
      Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      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

      If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

      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
      Comment `@coderabbitai help` to get the list of available commands.
    2. 🧹 Nitpick comments (1)
      packages/svelte-store/src/useSelector.svelte.ts (1)

      38-38: ⚡ Quick win

      Consider 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.md
      • packages/svelte-store/src/useSelector.svelte.ts
      • packages/svelte-store/tests/ProxyEquality.test.svelte
      • packages/svelte-store/tests/index.test.ts
    3. 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 (so useSelector via createTable), @tanstack/svelte-store@0.12.0, Svelte 5.56.4. Same path as #322: defaultCompare → Svelte's instrumented strict_equals → one warning per store notification.

      It isn't only a warning

      Isolated against @tanstack/svelte-store directly, 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).

      ArmSlicecompareEffect runsDistinct .current identities
      Aobjectdefault (===)44
      Bobject(a, b) => a.id === b.id11
      Cstringdefault (===)11

      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's set() calls proxy(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. So useSelector currently notifies on every store emission whatever the selector returns.

      Small supporting detail: strict_equals warns 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 / 4

      On the safety of $state.raw

      One behavioural change worth naming explicitly, since it's the thing that could hold up a merge: .current stops 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: slice is only ever reassigned, never mutated, exactly as the PR description says.

      Blast radius

      The whole public surface routes through useSelector — useAtom, useStore and _useStore all delegate to it — so this is object-slice behaviour for the package generally, not one entry point. Downstream it reaches @tanstack/svelte-table v9 (its createTable calls useSelector(table.store, selector) with no compare, 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.56 calls useSelector unchanged, svelte-store@0.12.0 is the latest release, and main still has let 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/tests alongside the test already in this PR if that would help.

    4. Happy to port this harness into packages/svelte-store/tests alongside 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.

    5. @KevinVandy / @crutchcorn — could one of you approve the workflow run on this PR?

    6. This still reproduces on current main (c1a40d4) and in 0.12.2.useSelector.svelte.ts#L38 still 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 main with state_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.

    7. 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

Sign in to join this conversation.