feat(react-virtual): add useVirtualizerSnapshot for React Compiler compatibility via useSyncExternalStore #1241
main fromrefs/pull/1241/head·opened 🎯 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(officialuse-sync-external-storeshim, so the>=16.8peer range is preserved):virtualItemsandtotalSizechange identity exactly when the computed geometry changes. The exported fields arereadonly/ReadonlyArray. - Imperative APIs stay on the stable instance (
snapshot.virtualizer):measureElementas 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.isScrollingflips) publish the same reference and skip the re-render (slightly fewer renders than the current adapter). - User
onChangechained;useFlushSyncsemantics preserved; SSR viagetServerSnapshot. - Shared engine (
useVirtualizerSnapshotBase) mirrors the existinguseVirtualizerBaselayering;virtual-coreuntouched. directDomUpdatesintentionally 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-compilerin CI — snapshot consumers emit the_c()memo cache,useVirtualizerconsumers remain skipped. If a compiler upgrade changes either half, CI says so. - E2E (3): a
snapshot-hookpage 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:
- 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.
- The two modes need different internal hooks (
useReducer+flushSyncvsuseSyncExternalStore), so a toggleable flag would require mounting both mechanisms unconditionally in the existing hot path, plus overloaded return types. - Separate hooks follow the package's own precedent (
useWindowVirtualizeris 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
useVirtualizerSnapshotanduseWindowVirtualizerSnapshothooks, providing immutablevirtualItems/totalSizefor render plus a stablevirtualizerfor imperative methods.
- Added React Compiler–compatible
- 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 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 Actionable comments posted: 3
🧹 Nitpick comments (1)
packages/react-virtual/tests/snapshot.test.tsx (1)
167-185: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExercise 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
observeWindowOffsetor 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.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (10)
.changeset/hungry-donkeys-applaud.mddocs/framework/react/react-virtual.mdpackages/react-virtual/e2e/app/react-compiler-vite.config.tspackages/react-virtual/e2e/app/snapshot-hook/index.htmlpackages/react-virtual/e2e/app/snapshot-hook/main.tsxpackages/react-virtual/e2e/app/test/snapshot-hook.spec.tspackages/react-virtual/package.jsonpackages/react-virtual/src/index.tsxpackages/react-virtual/tests/compiler.test.tspackages/react-virtual/tests/snapshot.test.tsx
@@ -33,3 +33,13 @@33333434 This function returns a window-based `Virtualizer` instance configured to work with the window as the scrollElement.353536+## `useVirtualizerSnapshot`37+38+```tsx39+function useVirtualizerSnapshot<TScrollElement, TItemElement = unknown>(40+ options: PartialKeys<41+ ReactVirtualizerSnapshotOptions<TScrollElement, TItemElement>,42+ 'observeElementRect' | 'observeElementOffset' | 'scrollToFn'43+ >,44+): VirtualizerSnapshot<TScrollElement, TItemElement>45+```🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== locate relevant files ==" git ls-files | rg '(^|/)docs/framework/react/react-virtual\.md$|react-virtual' | sed -n '1,120p' echo echo "== docs snippet ==" if [ -f docs/framework/react/react-virtual.md ]; then nl -ba docs/framework/react/react-virtual.md | sed -n '1,180p' fi echo echo "== search source definitions/usages ==" rg -n "useVirtualizerSnapshot|useWindowVirtualizerSnapshot|ReactVirtualizerSnapshotOptions|VirtualizerSnapshot|extends Element|TScrollElement|TItemElement" . --glob '!node_modules' --glob '!dist' --glob '!build' | sed -n '1,240p' echo echo "== if packages are visible, inspect package sources ==" find . -type f \( -name '*.ts' -o -name '*.tsx' -o -name '*.d.ts' \) | rg 'virtual|react' | sed -n '1,200p' | while read -r f; do if rg -q "useVirtualizerSnapshot|useWindowVirtualizerSnapshot|ReactVirtualizerSnapshotOptions|VirtualizerSnapshot" "$f"; then echo "--- $f" rg -n "interface|type|function useVirtualizerSnapshot|function useWindowVirtualizerSnapshot|ReactVirtualizerSnapshotOptions|VirtualizerSnapshot|implements|extends Element" "$f" | sed -n '1,160p' fi doneRepository: TanStack/virtual
Length of output: 2549
🏁 Script executed:
#!/bin/bash set -euo pipefail export LC_ALL=C echo "== docs react-virtual lines 1-180 ==" if [ -f docs/framework/react/react-virtual.md ]; then awk '{printf "%6d\t%s\n", NR, $0}' docs/framework/react/react-virtual.md | sed -n '1,180p' fi echo echo "== source definitions matching hook/type names ==" rg -n "type useVirtualizerSnapshot|function useVirtualizerSnapshot|useVirtualizerSnapshot|type useWindowVirtualizerSnapshot|function useWindowVirtualizerSnapshot|useWindowVirtualizerSnapshot|ReactVirtualizerSnapshotOptions|VirtualizerSnapshot" packages docs --glob '!e2e/**/*.spec.ts' | sed -n '1,240p' echo echo "== relevant snippets ==" python3 - <<'PY' from pathlib import Path files = [ Path('packages/react-virtual/src/index.tsx'), Path('docs/framework/react/react-virtual.md'), ] needle = {'useVirtualizerSnapshot','useWindowVirtualizerSnapshot','ReactVirtualizerSnapshotOptions','VirtualizerSnapshot','TScrollElement','TItemElement'} for p in files: if not p.exists(): continue lines = p.read_text(errors='replace').splitlines() hits=[] for i,l in enumerate(lines): if any(s in l for s in needle): hits.append((i+1,l)) print(f'--- {p} ({len(hits)} hits)') for nr,l in hits: start=max(1,nr-6); end=min(len(lines),nr+12) print(f'[{nr}]') for j in range(start,end+1): print(f'{j:4}\t{lines[j-1]}') print() PYRepository: TanStack/virtual
Length of output: 50374
🏁 Script executed:
#!/bin/bash set -euo pipefail python3 - <<'PY' from pathlib import Path import re doc = Path('docs/framework/react/react-virtual.md').read_text() src = Path('packages/react-virtual/src/index.tsx').read_text() for name, regex, expected in [ ('useVirtualizerSnapshot', r'export\s+function\s+useVirtualizerSnapshot\s*<\s*([^>{]+)>\s*\([^)]*options:\s*PartialKeys<\s*ReactVirtualizerSnapshotOptions<([^,]+),\s*([^>\n]+)', ('TScrollElement extends Element', 'Element', 'Element')), ('useWindowVirtualizerSnapshot', r'export\s+function\s+useWindowVirtualizerSnapshot\s*<\s*([^>{]+)>\s*\([^)]*options:\s*PartialKeys<\s*ReactVirtualizerSnapshotOptions<Window,\s*([^>\n]+)', (None, None, 'TItemElement extends Element')), ]: m = re.search(regex, src, re.S) print(f'{name}: found={bool(m)}') if m: print(' signature generics:', m.group(1).strip().replace('\n', ' ')) print(' matches expected:', all(x is None or x in m.group(0)) for x in [expected[0], expected[1], expected[2]]) # concise signature only print(' concise:', re.sub(r'\s+', ' ', m.group(0)[:240])) else: print(' expected:', expected) for name, expected_sig in [ ('useVirtualizerSnapshot', 'TScrollElement extends Element, TItemElement extends Element'), ('useWindowVirtualizerSnapshot', 'TItemElement extends Element'), ]: idx = doc.find(name) print(f'\nDoc {name}: found at index {idx}') if idx != -1: slice_ = doc[idx:idx+600] print(' snippet:') for line in slice_.splitlines()[:12]: print(line) print(' signature contains:', expected_sig in slice_) PYRepository: TanStack/virtual
Length of output: 469
Align the snapshot hook signatures with the exported TypeScript API.
docs/framework/react/react-virtual.md#L39-L45: constrainTScrollElement extends ElementandTItemElement extends Element; also update the documentedVirtualizerSnapshotwrapper to matchVirtualizerSnapshot<TScrollElement extends Element | Window, TItemElement extends Element>.docs/framework/react/react-virtual.md#L117-L125: documentTItemElement extends Element, notTItemElement = unknown.
📍 Affects 1 file
docs/framework/react/react-virtual.md#L39-L45(this comment)docs/framework/react/react-virtual.md#L117-L125
🤖 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 `@docs/framework/react/react-virtual.md` around lines 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.✅ Addressed in commit 420a871
Fixed in 420a8718 — both signature blocks now show the exported generic constraints (
TScrollElement extends Element,TItemElement extends Element, and theElement | Windowbound on the interface).@kklem0, thanks for fixing the documented generic constraints and theElement | Windowinterface bound.
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
@@ -35 +35,21 @@353536+## `useVirtualizerSnapshot`37+38+```tsx39+function useVirtualizerSnapshot<TScrollElement, TItemElement = unknown>(40+ options: PartialKeys<41+ ReactVirtualizerSnapshotOptions<TScrollElement, TItemElement>,42+ 'observeElementRect' | 'observeElementOffset' | 'scrollToFn'43+ >,44+): VirtualizerSnapshot<TScrollElement, TItemElement>45+```46+47+Like `useVirtualizer`, but returns the render-facing values as immutable48+snapshot data instead of methods to call during render:49+50+```tsx51+interface VirtualizerSnapshot<TScrollElement, TItemElement> {52+ virtualItems: Array<VirtualItem>53+ totalSize: number54+ virtualizer: Virtualizer<TScrollElement, TItemElement>55+}🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== locate file ==" git ls-files | rg '(^|/)react-virtual\.md$|VirtualizerSnapshot' echo "== file excerpt ==" if [ -f docs/framework/react/react-virtual.md ]; then nl -ba docs/framework/react/react-virtual.md | sed -n '1,120p' fi echo "== docs/framework/react usages/nearby ==" fd -a . docs/framework/react -t f 2>/dev/null | sed -n '1,80p' || true echo "== search VirtualizerSnapshot usages ==" rg -n "VirtualizerSnapshot|virtualItems|immutable snapshot|useVirtualizer" docs package.json pnpm-package-lock.json yarn.lock package-lock.json 2>/dev/null || true echo "== package references react virtual ==" rg -n "react-virtual|TanStack|Virtualizer|virtualItems" package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null || trueRepository: TanStack/virtual
Length of output: 269
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== file excerpt ==" if [ -f docs/framework/react/react-virtual.md ]; then awk '{printf "%6d\t%s\n", NR, $0}' docs/framework/react/react-virtual.md | sed -n '1,120p' fi echo "== search VirtualizerSnapshot usages ==" rg -n "VirtualizerSnapshot|virtualItems|immutable snapshot|useVirtualizer" docs package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null || true echo "== find framework docs files ==" find docs -maxdepth 4 -type f -print 2>/dev/null | sed -n '1,120p'Repository: TanStack/virtual
Length of output: 11065
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== find source files containing ReactVirtualizerSnapshotOptions / VirtualizerSnapshot ==" find . -type f \( -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.d.ts' \) -print 2>/dev/null | while read -r f; do if rg -q "ReactVirtualizerSnapshotOptions|VirtualizerSnapshot|getVirtualSnapshot|useVirtualizerSnapshot|virtualItems: Readonly" "$f"; then echo "--- $f" rg -n "ReactVirtualizerSnapshotOptions|VirtualizerSnapshot|getVirtualSnapshot|useVirtualizerSnapshot|virtualItems: Readonly|virtualItems: Array|virtualItems:" "$f" fi done echo "== candidate file excerpts ==" python3 - <<'PY' from pathlib import Path import subprocess files = subprocess.check_output(['git','ls-files'], text=True).splitlines() for f in [x for x in files if x.endswith(('.ts','.tsx','.js','.d.ts'))]: text = Path(f).read_text(errors='ignore').splitlines() hits = [i for i,line in enumerate(text) if 'ReactVirtualizerSnapshotOptions' in line or 'VirtualizerSnapshot' in line or 'getVirtualSnapshot' in line or 'useVirtualizerSnapshot' in line] if hits: for h in hits[:5]: start=max(0,h-8); end=min(len(text),h+18) print(f"--- {f}:{h+1}") for i in range(start,end): print(f"{i+1}\t{text[i]}") PYRepository: TanStack/virtual
Length of output: 146
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== tracked ts/tsx/js/d.ts files ==" git ls-files '*.ts' '*.tsx' '*.js' '*.d.ts' '*.json' | sed -n '1,200p' echo "== targeted search for snapshot types/usages ==" rg -n "ReactVirtualizerSnapshotOptions|VirtualizerSnapshot|getVirtualSnapshot|useVirtualizerSnapshot|useSyncExternalStore|virtualItems" --glob '*.ts' --glob '*.tsx' --glob '*.js' --glob '*.d.ts' .Repository: TanStack/virtual
Length of output: 17771
Expose
virtualItemsas read-only if immutability is guaranteed.useVirtualizerSnapshotpromises immutable snapshot data, butVirtualizerSnapshot.virtualItemsis typed asArray<VirtualItem>in both the package and docs, so consumers can still call mutating methods likepush/splice. UseReadonlyArray<VirtualItem>in the exported interface and matching doc type, or remove the immutability wording.🤖 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 `@docs/framework/react/react-virtual.md` around lines 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.✅ Addressed in commit 420a871
Fixed in 420a8718 —
ReadonlyArray<VirtualItem>+readonlyfields in both the exported interface and the docs.@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!
@@ -279,0 +298,21 @@298+ * The virtual items for the current visible range, as immutable snapshot299+ * data. The array reference changes when — and only when — the computed300+ * items change, so memoization keyed on it (manual or via React Compiler)301+ * stays correct.302+ */303+ virtualItems: Array<VirtualItem>304+ /**305+ * Total size of the virtualized extent, captured in the same snapshot as306+ * `virtualItems`.307+ */308+ totalSize: number309+ /**310+ * The underlying virtualizer instance, for imperative APIs only:311+ * `measureElement` (as a ref), `scrollToIndex`, `scrollToOffset`,312+ * `measure`, … Its identity is stable for the lifetime of the component.313+ *314+ * Do not read positional data (`getVirtualItems()`, `getTotalSize()`,315+ * `range`, `scrollOffset`, …) from it during render — those reads are what316+ * memoizing compilers cache stale (#736). Use the snapshot fields instead.317+ */318+ virtualizer: Virtualizer<TScrollElement, TItemElement>🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Publish an actually immutable snapshot.
Lines 303 and 365 expose the mutable core-owned array directly, and the returned snapshot object itself has writable fields. A consumer can mutate/sort items and poison the cached value used by subsequent renders. Expose readonly fields and cache a cloned, frozen item snapshot when the core array identity changes.
Proposed fix
export interface VirtualizerSnapshot<...> { - virtualItems: Array<VirtualItem> - totalSize: number - virtualizer: Virtualizer<TScrollElement, TItemElement> + readonly virtualItems: ReadonlyArray<Readonly<VirtualItem>> + readonly totalSize: number + readonly virtualizer: Virtualizer<TScrollElement, TItemElement> } +let sourceVirtualItems: Array<VirtualItem> | null = null ... - if (snapshot === null || snapshot.virtualItems !== virtualItems || snapshot.totalSize !== totalSize) { - snapshot = { virtualItems, totalSize } + if (snapshot === null || sourceVirtualItems !== virtualItems || snapshot.totalSize !== totalSize) { + sourceVirtualItems = virtualItems + snapshot = { + virtualItems: Object.freeze( + virtualItems.map((item) => Object.freeze({ ...item })), + ), + totalSize, + } }Also applies to: 333-373, 414-420
🤖 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/src/index.tsx` around lines 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.Addressed the type half in 420a8718:
VirtualizerSnapshotfields are nowreadonlyandvirtualItemsis aReadonlyArray<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.freezein 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.@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.
kklem0(GitHub profile, opens in a new tab)replied on
packages/react-virtual/src/index.tsxlines 293 to 318Addressed the type half in 420a8718:
VirtualizerSnapshotfields are nowreadonlyandvirtualItemsis aReadonlyArray<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.freezein 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.kklem0(GitHub profile, opens in a new tab)replied on
docs/framework/react/react-virtual.mdlines 39 to 45Fixed in 420a8718 — both signature blocks now show the exported generic constraints (
TScrollElement extends Element,TItemElement extends Element, and theElement | Windowbound on the interface).kklem0(GitHub profile, opens in a new tab)replied on
docs/framework/react/react-virtual.mdlines 50 to 61Fixed in 420a8718 —
ReadonlyArray<VirtualItem>+readonlyfields in both the exported interface and the docs.Re the CodeRabbit ESLint tool failures on the two new test files:
packages/react-virtual/tsconfig.jsonincludes onlysrc,vite.config.ts, andplaywright.config.ts— test files sit outside the type-aware project repo-wide (the pre-existingtests/index.test.tsxhas 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.coderabbitai[bot](GitHub profile, opens in a new tab)replied on
docs/framework/react/react-virtual.mdlines 39 to 45@kklem0, thanks for fixing the documented generic constraints and theElement | Windowinterface bound.
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
coderabbitai[bot](GitHub profile, opens in a new tab)replied on
docs/framework/react/react-virtual.mdlines 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!
coderabbitai[bot](GitHub profile, opens in a new tab)replied on
packages/react-virtual/src/index.tsxlines 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.
🧹 Nitpick comments (2)
packages/react-virtual/tests/snapshot.test.tsx (2)
117-140: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAlso assert stable
virtualizeridentity after thegapupdate.This test verifies stability after the
countchange but not after the second render-time geometry update. Add the same assertion forafterGapChangeto 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 winExercise a window-scroll update, not only initial rendering.
The current smoke test can pass even if
useWindowVirtualizerSnapshotfails 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.mdpackages/react-virtual/src/index.tsxpackages/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
kklem0(GitHub profile, opens in a new tab) changed the title
kklem0(GitHub profile, opens in a new tab) changed the title
Sign in to join this conversation.
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_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
Adds
useVirtualizerSnapshotanduseWindowVirtualizerSnapshot, exposing immutable render snapshots with stable imperative virtualizer instances. The implementation usesuseSyncExternalStoreand includes compiler, unit, SSR, window-scrolling, documentation, and end-to-end regression coverage.Changes#
Snapshot virtualizer hooks
packages/react-virtual/src/index.tsx,packages/react-virtual/package.jsonuseSyncExternalStore, with stable virtualizer references and element/window scrolling wrappers.packages/react-virtual/tests/snapshot.test.tsx,packages/react-virtual/tests/compiler.test.tspackages/react-virtual/e2e/app/...,packages/react-virtual/e2e/app/test/snapshot-hook.spec.tsdocs/framework/react/react-virtual.md,.changeset/hungry-donkeys-applaud.mdEstimated code review effort: 3 (Moderate) | ~25 minutes
Sequence Diagram(s)#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
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