Skip to content
Source
Sign inSign up
TanStack/virtual

feat(react-virtual): add useVirtualizerSnapshot for React Compiler compatibility via useSyncExternalStore #1241

Openkklem0(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/1241/headopened

🎯 Changes

Adds useVirtualizerSnapshot and useWindowVirtualizerSnapshot: variants of the existing hooks whose render-facing values arrive as immutable snapshot data, making consuming components compatible with React Compiler.

Problem

React Compiler ships a hardcoded knownIncompatible entry for useVirtualizer ("returns functions that cannot be memoized safely") and skips every component that calls it — correct, but it leaves large consuming components entirely un-memoized (#1119).

The root cause is structural: useVirtualizer returns one identity-stable instance whose getVirtualItems() / getTotalSize() read mutable internal state during render, with re-renders forced by a contentless reducer bump. A memoizing compiler keys caches on reactive inputs — and the only input it can see is the never-changing instance:

// what the compiler generates for a consumer (mimic, since the real hook is skip-listed):
if ($[0] !== virtualizer) {            // identity-stable → true once, ever
  const items = virtualizer.getVirtualItems();
  t0 = <div>{items.map(...)}</div>;
  $[0] = virtualizer; $[1] = t0;
} else {
  t0 = $[1];                           // ← the first render's items, forever (#736, #743)
}

directDomUpdates (#1187) mitigates scroll-path cost under the skip; this PR adds the complementary path: letting consumers actually compile.

Design

The snapshot hooks split the API along the exact line the compiler cares about:

  • Render-facing values become immutable snapshot data via useSyncExternalStore (official use-sync-external-store shim, so the >=16.8 peer range is preserved): virtualItems and totalSize change identity exactly when the computed geometry changes. The exported fields are readonly / ReadonlyArray.
  • Imperative APIs stay on the stable instance (snapshot.virtualizer): measureElement as a ref, scrollToIndex, measure, … — these were never the problem (called at commit/event time, identity-stable, no ref churn).

Because the compiler's skip is keyed on the imported property name, snapshot consumers compile with today's stable compiler (1.0.0) — no coordination required. Longer term this also gives the React team a delisting target: the snapshot contract is compatible by design, not by exemption.

Implementation notes:

  • Snapshot rebuilt lazily on onChange, with part-comparison — notifications that change nothing visible (e.g. isScrolling flips) publish the same reference and skip the re-render (slightly fewer renders than the current adapter).
  • User onChange chained; useFlushSync semantics preserved; SSR via getServerSnapshot.
  • Shared engine (useVirtualizerSnapshotBase) mirrors the existing useVirtualizerBase layering; virtual-core untouched.
  • directDomUpdates intentionally not supported on the snapshot hooks — it's the alternative strategy (bypass React on scroll), while this makes React rendering itself compiler-safe.

Tests

  • Unit (6): initial range; referential stability across unrelated re-renders (the compiler contract); fresh identity on scroll; StrictMode; SSR; window variant.
  • Compiler contract (2): runs babel-plugin-react-compiler in CI — snapshot consumers emit the _c() memo cache, useVirtualizer consumers remain skipped. If a compiler upgrade changes either half, CI says so.
  • E2E (3): a snapshot-hook page added to the existing react-compiler build (from #1187): items render, update after scrolling (the #736 scenario, now passing with the consumer compiled), commit-count sanity.

Real-world validation

Linked this branch into a production React Router app (24 locales, Capacitor iOS/Android) that had isolated all eight of its virtualized lists behind the compiler skip. Converting a list to the snapshot hooks: the component went from compilation skipped to fully compiled (_c(26)), with types and lint clean, and identical runtime behavior.

Alternative considered: useVirtualizer({ snapshot: true })

An opt-in flag on the existing hooks would unify the API surface, but:

  1. The compiler's skip is name-keyed and not options-aware, so flagged consumers would still be skipped — the flag can't deliver the compiler benefit that motivates the feature.
  2. The two modes need different internal hooks (useReducer+flushSync vs useSyncExternalStore), so a toggleable flag would require mounting both mechanisms unconditionally in the existing hot path, plus overloaded return types.
  3. Separate hooks follow the package's own precedent (useWindowVirtualizer is a hook, not a { window: true } flag).

Happy to restructure if you prefer the flag shape — the engine converts trivially.

Refs: #736, #743, #1119, #1187

✅ 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

  • New Features
    • Added React Compiler–compatible useVirtualizerSnapshot and useWindowVirtualizerSnapshot hooks, providing immutable virtualItems/totalSize for render plus a stable virtualizer for imperative methods.
  • Documentation
    • Updated React Virtual docs with snapshot-hook guidance and compiler-compatibility constraints.
  • Bug Fixes
    • Resolved a regression affecting compiled consumers’ virtualization rendering and scrolling updates.
  • Tests
    • Added unit, compiler, and end-to-end regression coverage for snapshot behavior and scroll/commit updates.
  • Chores
    • Updated dependency to support snapshot subscriptions.
    1. Review Change Stack

      Note

      Reviews paused

      It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

      Use the following commands to manage reviews:

      • @coderabbitai resume to resume automatic reviews.
      • @coderabbitai review to trigger a single review.

      Use the checkboxes below for quick actions:

      • ▶️ Resume reviews
      • 🔍 Trigger review
      📝 Walkthrough

      Walkthrough

      Adds useVirtualizerSnapshot and useWindowVirtualizerSnapshot, exposing immutable render snapshots with stable imperative virtualizer instances. The implementation uses useSyncExternalStore and includes compiler, unit, SSR, window-scrolling, documentation, and end-to-end regression coverage.

      Changes

      Snapshot virtualizer hooks

      Layer / File(s)Summary
      Snapshot API and subscription implementation
      packages/react-virtual/src/index.tsx, packages/react-virtual/package.json
      Adds snapshot types and hooks backed by useSyncExternalStore, with stable virtualizer references and element/window scrolling wrappers.
      Snapshot and compiler validation
      packages/react-virtual/tests/snapshot.test.tsx, packages/react-virtual/tests/compiler.test.ts
      Covers rendering, identity stability, updates, StrictMode, SSR, window scrolling, and React Compiler compilation behavior.
      React Compiler end-to-end regression coverage
      packages/react-virtual/e2e/app/..., packages/react-virtual/e2e/app/test/snapshot-hook.spec.ts
      Adds a compiled demo and Playwright checks for initial virtualization, scrolling updates, row positioning, and rerenders.
      Snapshot hook documentation and release entry
      docs/framework/react/react-virtual.md, .changeset/hungry-donkeys-applaud.md
      Documents snapshot APIs, compiler usage, imperative access, and the new release entry.

      Estimated code review effort: 3 (Moderate) | ~25 minutes

      Sequence Diagram(s)

      sequenceDiagram
        participant ReactComponent
        participant useVirtualizerSnapshot
        participant Virtualizer
        participant useSyncExternalStore
        ReactComponent->>useVirtualizerSnapshot: call with virtualization options
        useVirtualizerSnapshot->>Virtualizer: create and update virtualizer
        Virtualizer->>useSyncExternalStore: publish onChange notification
        useSyncExternalStore-->>ReactComponent: provide virtualItems and totalSize snapshot
        ReactComponent->>Virtualizer: call scrollToIndex through snapshot.virtualizer
        Virtualizer->>useSyncExternalStore: publish updated visible items
        useSyncExternalStore-->>ReactComponent: rerender with new snapshot
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 37.50% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Title check✅ PassedThe title clearly identifies the new snapshot hook and its React Compiler compatibility purpose, despite the minor typo “vis.”
      Description check✅ PassedThe description explains the changes, motivation, design, tests, release impact, checklist, and generated changeset.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      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. Review the following changes in direct dependencies. Learn more about Socket for GitHub.

      Diff Package Supply Chain
      Security
      Vulnerability Quality Maintenance License
      Added@​types/​use-sync-external-store@​1.5.01001006280100

      View full report

    3. Actionable comments posted: 3

      🧹 Nitpick comments (1)
      packages/react-virtual/tests/snapshot.test.tsx (1)

      167-185: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Exercise window scroll updates.

      This only verifies the initial window snapshot. Add an offset/scroll update assertion that confirms a changed window position publishes a new range; otherwise regressions in observeWindowOffset or the window wrapper remain untested.

      🤖 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/react-virtual/tests/snapshot.test.tsx` around lines 167 - 185,
      Extend the useWindowVirtualizerSnapshot test around WindowList to simulate a
      window scroll or offset change after the initial render, then assert that the
      rendered virtual-item range updates to reflect the new position. Keep the
      existing Row 0 initial assertion and use the public window-offset update path so
      observeWindowOffset and its wrapper are exercised.
      🤖 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.
      
      Inline comments:
      In `@docs/framework/react/react-virtual.md`:
      - Around line 39-45: Align the documented React virtualizer snapshot signatures
      with the exported TypeScript API: at docs/framework/react/react-virtual.md lines
      39-45, constrain TScrollElement and TItemElement to Element and update the
      VirtualizerSnapshot wrapper to use TScrollElement extends Element | Window and
      TItemElement extends Element; at lines 117-125, document TItemElement extends
      Element instead of defaulting it to unknown.
      - Around line 47-55: Update the exported VirtualizerSnapshot interface and its
      matching documentation type to declare virtualItems as
      ReadonlyArray<VirtualItem> rather than Array<VirtualItem>. Preserve the existing
      immutable snapshot contract and useVirtualizerSnapshot behavior.
      
      In `@packages/react-virtual/src/index.tsx`:
      - Around line 293-318: Update VirtualizerSnapshot and its snapshot construction
      path to expose readonly fields, and prevent consumers from mutating cached data.
      When the core virtual-items array identity changes, create and cache a cloned,
      frozen array; reuse it otherwise, and freeze the returned snapshot object while
      preserving the existing virtualizer, totalSize, and memoization behavior.
      
      ---
      
      Nitpick comments:
      In `@packages/react-virtual/tests/snapshot.test.tsx`:
      - Around line 167-185: Extend the useWindowVirtualizerSnapshot test around
      WindowList to simulate a window scroll or offset change after the initial
      render, then assert that the rendered virtual-item range updates to reflect the
      new position. Keep the existing Row 0 initial assertion and use the public
      window-offset update path so observeWindowOffset and its wrapper are exercised.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 33367ede-5cbe-47dd-8e67-977931c6c9c2

      📥 Commits

      Reviewing files that changed from the base of the PR and between deca524a9b2ed29a8a23001389580de10f8002db and b38b92e57dd4cb3437d753b9891e366aaac0dbe6.

      ⛔ Files ignored due to path filters (1)
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (10)
      • .changeset/hungry-donkeys-applaud.md
      • docs/framework/react/react-virtual.md
      • packages/react-virtual/e2e/app/react-compiler-vite.config.ts
      • packages/react-virtual/e2e/app/snapshot-hook/index.html
      • packages/react-virtual/e2e/app/snapshot-hook/main.tsx
      • packages/react-virtual/e2e/app/test/snapshot-hook.spec.ts
      • packages/react-virtual/package.json
      • packages/react-virtual/src/index.tsx
      • packages/react-virtual/tests/compiler.test.ts
      • packages/react-virtual/tests/snapshot.test.tsx
      OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
    4. kklem0(GitHub profile, opens in a new tab)replied on packages/react-virtual/src/index.tsx lines 293 to 318

      Addressed the type half in 420a8718: VirtualizerSnapshot fields are now readonly and virtualItems is a ReadonlyArray<VirtualItem>, so mutation is a compile-time error for TS consumers, and the JSDoc spells out that the reference is shared with the core.

      On cloning/freezing at runtime: I'd argue against it. The exposed array is the same core-owned memoized reference that every existing getVirtualItems() consumer already receives — the snapshot hooks add no new exposure relative to the package's current contract — and cloning on every geometry change adds hot-path allocations in exactly the code virtualization exists to keep cheap. Object.freeze in dev would be a package-wide policy question (none of the existing APIs freeze their returns), so I've left runtime behavior consistent with the rest of the package. Happy to add dev-only freezing if the maintainers want it as policy.

    5. kklem0(GitHub profile, opens in a new tab)replied on docs/framework/react/react-virtual.md lines 39 to 45

      Fixed in 420a8718 — both signature blocks now show the exported generic constraints (TScrollElement extends Element, TItemElement extends Element, and the Element | Window bound on the interface).

    6. kklem0(GitHub profile, opens in a new tab)replied on docs/framework/react/react-virtual.md lines 50 to 61

      Fixed in 420a8718 — ReadonlyArray<VirtualItem> + readonly fields in both the exported interface and the docs.

    7. Re the CodeRabbit ESLint tool failures on the two new test files: packages/react-virtual/tsconfig.json includes only src, vite.config.ts, and playwright.config.ts — test files sit outside the type-aware project repo-wide (the pre-existing tests/index.test.tsx has the same status; it just wasn't linted here because only changed files are). The new tests follow the existing convention; happy to widen the tsconfig include in a separate change if that's preferred.

    8. coderabbitai[bot](GitHub profile, opens in a new tab)replied on docs/framework/react/react-virtual.md lines 39 to 45

      @kklem0, thanks for fixing the documented generic constraints and the Element | Window interface bound.


      If you found this review helpful, would you consider giving us a shout-out on X?

      Thank you for using CodeRabbit!

    9. coderabbitai[bot](GitHub profile, opens in a new tab)replied on docs/framework/react/react-virtual.md lines 50 to 61

      @kklem0, thanks for fixing this. The read-only snapshot contract is now reflected in both the exported type and documentation. 🎉


      If you found this review helpful, would you consider giving us a shout-out on X?

      Thank you for using CodeRabbit!

    10. coderabbitai[bot](GitHub profile, opens in a new tab)replied on packages/react-virtual/src/index.tsx lines 293 to 318

      @kklem0, agreed. The readonly types and explicit shared-reference documentation establish the intended consumer contract, while cloning/freezing would introduce a new package-wide runtime policy and unnecessary hot-path allocations. I’m withdrawing the runtime-immutability portion of this finding.


      ✏️ Learnings added
      Learnt from: kklem0
      Repo: TanStack/virtual PR: 1241
      File: packages/react-virtual/src/index.tsx:0-0
      Timestamp: 2026-07-25T01:41:23.256Z
      Learning: In `packages/react-virtual/src/index.tsx`, `VirtualizerSnapshot.virtualItems` intentionally exposes the same core-owned memoized array returned by `Virtualizer.getVirtualItems()`. It is typed as `ReadonlyArray<VirtualItem>` and documented as read-only, but is not cloned or runtime-frozen to preserve the existing package contract and avoid allocations on geometry-update hot paths.

      Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

    11. 🧹 Nitpick comments (2)
      packages/react-virtual/tests/snapshot.test.tsx (2)

      117-140: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

      Also assert stable virtualizer identity after the gap update.

      This test verifies stability after the count change but not after the second render-time geometry update. Add the same assertion for afterGapChange to protect the imperative instance contract.

      Proposed assertion
       expect(afterGapChange.virtualItems).not.toBe(afterCountChange.virtualItems)
      +expect(afterGapChange.virtualizer).toBe(afterCountChange.virtualizer)
      🤖 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/react-virtual/tests/snapshot.test.tsx` around lines 117 - 140, Add
      an assertion in the render-time geometry update test after the gap rerender to
      verify afterGapChange.virtualizer is the same object as
      afterCountChange.virtualizer, preserving the existing virtualizer identity
      contract.

      198-216: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

      Exercise a window-scroll update, not only initial rendering.

      The current smoke test can pass even if useWindowVirtualizerSnapshot fails to publish updates from the window offset observer. Scroll the window and assert that the rendered range or snapshot changes.

      🤖 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/react-virtual/tests/snapshot.test.tsx` around lines 198 - 216,
      Extend the useWindowVirtualizerSnapshot test to simulate scrolling the window
      after the initial render and assert that the rendered virtual range or snapshot
      updates accordingly. Keep the existing initial Row 0 assertion, and use the
      test’s rendered WindowList output and window-scroll behavior to verify
      observer-driven updates rather than only initial rendering.
      🤖 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/react-virtual/tests/snapshot.test.tsx`:
      - Around line 117-140: Add an assertion in the render-time geometry update test
      after the gap rerender to verify afterGapChange.virtualizer is the same object
      as afterCountChange.virtualizer, preserving the existing virtualizer identity
      contract.
      - Around line 198-216: Extend the useWindowVirtualizerSnapshot test to simulate
      scrolling the window after the initial render and assert that the rendered
      virtual range or snapshot updates accordingly. Keep the existing initial Row 0
      assertion, and use the test’s rendered WindowList output and window-scroll
      behavior to verify observer-driven updates rather than only initial rendering.

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: d32ff408-209d-48ef-8e60-70d3ca60118a

      📥 Commits

      Reviewing files that changed from the base of the PR and between 420a87187bb4e376377a6fde39112144d05cc91b and e7fc53561d58a7eab20a28976d372362b86c331f.

      📒 Files selected for processing (3)
      • docs/framework/react/react-virtual.md
      • packages/react-virtual/src/index.tsx
      • packages/react-virtual/tests/snapshot.test.tsx
      🚧 Files skipped from review as they are similar to previous changes (2)
      • docs/framework/react/react-virtual.md
      • packages/react-virtual/src/index.tsx
    12. kklem0(GitHub profile, opens in a new tab) changed the title

    13. kklem0(GitHub profile, opens in a new tab) changed the title

Sign in to join this conversation.