refactor(react-virtual): subscribe to virtualizer updates with useSyncExternalStore #1259
main fromrefs/pull/1259/head·opened 🎯 Changes#
Drives useVirtualizer / useWindowVirtualizer re-renders through useSyncExternalStore instead of a useReducer bump. The public API, the returned instance and its identity semantics are unchanged — consumers keep calling getVirtualItems() / getTotalSize() on the instance.
This is the direction suggested in #851 ("useSyncExternalStore feels like a more natural fit compared to useMemo"), applied to the existing hooks rather than as a separate hook: no new hook names, no API change, and nothing that tries to work around React Compiler's knownIncompatible entry for useVirtualizer.
It is the minimal alternative to #1241 (which adds separate useVirtualizerSnapshot hooks). Both are open on purpose so you can pick the shape you prefer — they don't have to be exclusive, see the React Compiler note below.
Design#
- Store: a tiny external store whose snapshot is a version counter, bumped by every notification the adapter decides to render (
directDomUpdatesgating is untouched). The counter tells React that the instance moved; consumers still read render-facing values from the instance. useFlushSyncpreserved: the synchronous scroll path notifies insideflushSync, so the DOM still updates before the scroll handler returns.- Before-paint catch-up:
useSyncExternalStoresubscribes in a passive effect, so notifications raised while React is committing — the initial rect/offset measurement in_willUpdate, scroll-element swaps,measureElementrefs for freshly mounted items — have no listener yet and would only surface via the store's post-commit check, i.e. after paint (a visible flash of the unmeasured range on heavy initial renders). A final layout effect compares the store version with the rendered one and dispatches a reducer so those still re-render synchronously before paint, exactly as before. Mount / measure render counts in the existing tests are unchanged (2 and 3). - Shim:
use-sync-external-store/shim(React's official package) keeps the^16.8 || ^17 || ^18 || ^19peer range; on React 18+ it isReact.useSyncExternalStore. - SSR:
getServerSnapshotprovided;renderToStringcovered by a test.
Why#
- Under concurrent rendering (transitions, Suspense,
useDeferredValue) a reducer bump scheduled while a render is in progress lets React finish and commit that render with the stale range it already read, then re-render. WithuseSyncExternalStoreReact checks the store at the end of a non-blocking render and re-renders synchronously if it moved, so a torn frame is never committed. - The virtualizer is an external mutable store read during render;
useSyncExternalStoreis the primitive React provides for that.
Tests#
- Existing suite unchanged and passing.
- New: scroll notifications through the store (range +
isScrollingflip),useFlushSyncsync commit vs. React-scheduled commit outsideact, SSR viagetServerSnapshot, StrictMode, no updates after unmount. pnpm run test:prlocally: eslint, types, lib, build/publint, sherif, knip, and the full react-virtual Playwright suite (33 tests, incl.react-compileranddirect-dom-updates).
Note on React Compiler / knownIncompatible#
React Compiler ships a hardcoded knownIncompatible entry for @tanstack/react-virtual's useVirtualizer and skips every component that calls it (#1119). This PR deliberately does not change that, and doesn't try to work around it:
- The skip is keyed on the import name, and the returned instance stays identity-stable by design, so a compiled consumer would still memoize
getVirtualItems()on it (#736, #743). The entry stays accurate for now; this PR only changes how the adapter subscribes. - What it does do is put the adapter on the primitive the compiler story needs — a real store with a snapshot — so the remaining gap is purely the shape of the render-facing values, not the subscription mechanism.
Possible follow-ups, as separate PRs, whichever you prefer:
- Alias hook — a companion built on the same store that returns the render-facing values as immutable data (
virtualItems,totalSize) next to the stable instance for imperative calls. #1241 is one concrete shape of that; it can be rebased onto this store. - Upstream delisting — once a compiler-safe contract exists, work with the React team to drop (or narrow) the
knownIncompatibleentry, so consumers compile without renaming imports.
Refs: #851, #736, #743, #1119, #1241
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm run 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
- Improved rendering consistency for virtualized content during concurrent rendering.
- Ensured updates are applied synchronously when needed, reducing visual inconsistencies before paint.
- Improved reliability across server-rendered, Strict Mode, and unmounted component scenarios.
- Compatibility
- Preserved existing virtualizer APIs and React 16.8+ support.
- 1
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
Diff Package Supply Chain
SecurityVulnerability Quality Maintenance License @types/use-sync-external-store@1.5.0 thoughts? @piecyk @tannerlinsley
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:
807f919d-2dfe-4818-826f-d14a2a8c5e32📥 Commits
Reviewing files that changed from the base of the PR and between e9874f033c74afd3251eeb9f3e60b2530cc7ae88 and 83cdb85737201b4c96ae63b7794e7e438bdaeabf.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml📒 Files selected for processing (4)
.changeset/quiet-stores-listen.mdpackages/react-virtual/package.jsonpackages/react-virtual/src/index.tsxpackages/react-virtual/tests/index.test.tsxIncluded review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review.
📝 Walkthrough
Walkthrough#
useVirtualizerBasenow usesuseSyncExternalStorewith a versioned listener store. Tests cover notification timing, SSR, StrictMode, and unmount behavior. The React peer range and virtualizer APIs remain unchanged.Changes#
React virtualizer store
packages/react-virtual/src/index.tsx,packages/react-virtual/package.json,.changeset/quiet-stores-listen.mduseSyncExternalStore. Notifications supportflushSync, and a final layout effect reconciles updates before paint. The required runtime and type packages are declared.packages/react-virtual/tests/index.test.tsxEstimated code review effort: 3 (Moderate) | ~20 minutes
Merge Risk: ⚪ Minimal · up to
83cdbThis refactors virtualizer update subscriptions without changing the public API or instance identity semantics; the reported validation passes, and no actionable merge-blocking risk remains.
Sequence Diagram(s)#
Suggested reviewers:
piecyk🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Warning
Some tools did not complete. Review the errors below.
🔧 ESLint
packages/react-virtual/tests/index.test.tsx
Parsing error: "parserOptions.project" has been provided for
@typescript-eslint/parser. The file was not found in any of the provided project(s): packages/react-virtual/tests/index.test.tsxThanks 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