Skip to content
Source
Sign inSign up
TanStack/virtual

perf: virtual-core rewrite for mount/measure-storm, plus iOS Safari handling and scroll restoration #1168

Mergedtannerlinsleymerged 43 commits intomain fromrefs/pull/1168/headmerged by tannerlinsley

tannerlinsleycommented

Summary

A perf-focused release covering several themes. Release blog post at tanstack.com#934.

Six changesets:

BumpPackageTheme
minor@tanstack/virtual-coreLazy VirtualItem materialization (typed-array + Proxy) for the lanes===1 fast path, plus eight smaller audit hotfixes (Map clone, setOptions deopt, Math.min spread, defaultRangeExtractor allocation, elementsCache leak, etc.)
minor@tanstack/virtual-coreiOS Safari momentum-scroll handling (touch event distinction, subpixel reconciliation, elastic-overscroll clamp)
minor@tanstack/virtual-coreSkip scroll-position adjustment on backward scroll by default (closes the largest single complaint cluster)
minor@tanstack/virtual-coreNew takeSnapshot() public method for scroll-restoration round-trips
patch@tanstack/virtual-corescrollToIndex(N, { behavior: 'smooth' }) keeps smooth while still > viewport away from target instead of snapping to 'auto' on first retarget
patch@tanstack/react-virtualUse a number counter for the force-rerender pattern, dropping the {} allocation per scroll dispatch

Headline numbers

MetricBeforeAfter
Cold mount @ 100k items (real React)6.1 ms4.5 ms
Cold mount @ 100k items (synthetic)2.5 ms0.54 ms
Cold mount @ 500k items (synthetic)14 ms2.7 ms
resizeItem storm on 10k items1.9 s1.3 ms
setOptions × 10,000 (per render)14.4 ms1.3 ms
scrollToIndex landing accuracy (dynamic 10k)within 1 px0.0 px
iOS Safari momentum scrollbrokenworks
Backward-scroll jank with dynamic itemsrecurringgone by default

The 1382x resizeItem win is real and embarrassing in equal measure (Map clone on every resize purely to invalidate a memo dep).

Bundle size

Buildorigin/mainThis PRDelta
Consumer-minified gzip (esbuild prod)5.22 kB6.11 kB+890 B (+17%)

About 430 B for the lazy-materialization machinery, 370 B for iOS handling, and 90 B for the rest of the fixes combined.

Behavior changes

Three default changes consumers should know about:

  1. Backward-scroll no longer writes scrollTop on above-viewport resize by default. Users who relied on the old behavior can supply shouldAdjustScrollPositionOnItemSizeChange.
  2. iOS Safari adjustments are deferred until scroll settles. Invisible to most users; fixes recurring bug reports.
  3. setOptions no longer mutates the caller's options object (hidden contract violation; unlikely anyone was relying on the mutation).

What's new

  • virtualizer.takeSnapshot() — returns currently-measured items as plain VirtualItem objects, pairs with initialMeasurementsCache for scroll restoration after navigation. Documented in docs/api/virtualizer.md.
  • initialMeasurementsCache is now documented (was previously undocumented even though the option already existed).

New tests

91 unit tests across virtual-core and react-virtual, up from 13 originally. New coverage for: lazy fast-path edge cases (9), iOS deferral (7), subpixel reconciliation (3), elastic-overscroll clamp (3), backward-scroll skip (3), takeSnapshot round-trip (2), several smaller audit-driven regression tests.

Reproducible benchmark suite

Added benchmarks/ — a Vite app + Playwright runner that drives the same scenarios across @tanstack/react-virtual and the other major virtualization libraries and reports medians across runs. Documented in benchmarks/README.md. Run with cd benchmarks && pnpm bench. Useful as a regression guard for future perf work.

Test plan

  • pnpm test:lib (91/91 passing)
  • pnpm test:types
  • pnpm test:eslint
  • pnpm test:build
  • pnpm test:knip
  • pnpm test:sherif
  • pnpm test:docs (link check)
  • pnpm changeset schema validates
  • React-virtual integration tests (6/6 passing)
  • Cross-library benchmark suite runs end-to-end
  • Optional: rerun pnpm bench on reviewer's machine to confirm numbers
  • Optional: pnpm changeset:version preview before merging

Pre-existing lit-virtual:build and :test:e2e failures on main are unrelated to this PR.

Summary by CodeRabbit

  • New Features

    • Added takeSnapshot() and initialMeasurementsCache for snapshot/restore.
    • Default iOS Safari momentum-scroll protections enabled.
    • Skip scroll-position adjustment when scrolling backward by default.
  • Bug Fixes

    • Smooth scroll preserves smooth behavior on dynamic-height lists; final landing accuracy improved.
    • Prevented upward-scroll jank from above-viewport resizes.
  • Performance

    • Lower allocations and faster cold-mounts via lazy measurements and hot-path optimizations.
    • Reduced per-dispatch allocations in React integration.
  • Benchmarks

    • New reproducible browser benchmark harness, runner, datasets and sample results; added benchmarks workspace.
  • Documentation

    • Updated Virtualizer API docs for new options and methods.
  • Tests

    • Expanded coverage and benchmarks for scroll, measurement, iOS, and reconciliation behaviors.

Review Change Stack

    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: e4427df1-ff77-4d56-9e98-ff5a8a116f34

      📥 Commits

      Reviewing files that changed from the base of the PR and between ab9c00fe811d0cc00b000b89429b593f5080ae2d and 186b3bd60dd1f050270ca62ecfc7d968f79e3a11.

      📒 Files selected for processing (2)
      • .changeset/fix-core-elementscache-stale-index.md
      • packages/virtual-core/src/index.ts
      ✅ Files skipped from review due to trivial changes (1)
      • .changeset/fix-core-elementscache-stale-index.md

      📝 Walkthrough Virtual core + benchmarks: complete change stack All changes in this PR: changesets, docs, benchmarks, virtual-core core refactors (typed-array fast path, iOS scroll handling, reconciliation, takeSnapshot), tests, and small react-virtual tweak. Single cohesive cohort covering the full set of related changes in the PR: release notes, benchmark workspace, core library implementation and optimizations, tests, and docs. Contains every changed rangeId for the PR. Reviewers should inspect in semantic order: release/docs, benchmark infra, core implementation (utils, observers, flat measurements, fast paths, resize/scroll handling, snapshot), tests/benches. range_437920e6a8c0 range_5643668018b9 range_c9a37415b5ea range_384c7e8bef1a range_210458182c88 range_8762c85a993a range_ca54fd3e3f94 range_fa8b74866f17 range_5b22db72b1e4 range_c7a94c20fe62 range_64102c1564cb range_42e54b5fe3b3 range_a22116d5b35d range_36b56d720385 range_0d023021201b range_6fbe0c37f866 range_0e74dbf43d41 range_a4cac3aff091 range_7e0e5d5377aa range_23a922dec5b2 range_22cc6fbe9438 range_e56fb78142de range_a1ad641aabd7 range_35d4101fd7ba range_7e1df3bdf167 range_5d5ceb82beab range_5b0245d47bff range_cdfd770b85f6 range_2c7899417251 range_d80dda1138f5 range_303baa9d37ba range_c8d0c8cc76c0 range_38ca836ce913 range_117b77b2a752 range_6bb647ac17b5 range_706867e6afee range_2b5379b9a5c4 range_96e215b0c73d range_5e4c7f2de1d9 range_0592d69c30e5 range_65581c125258 range_0f3a73e835d1 range_8dc5734c92ec range_0f4fb3489b76 range_579e1360e569 range_dcf586b99541 range_b1595d3902c6 range_c6ec57ed6a61 range_de78d6e3d1a4 range_0dbdf14ead32 range_5eca6e8056e5 range_0332ea734df0 range_a5e508142235 range_d55b7eab19dc range_afe8b94fc289 range_0746f3768ce8 range_1a3d5b3401ae range_638b5348b44e range_4e01fa951029 range_c452511863a0 range_c5287f6ea393 range_4e36dda31725 range_89d4d627707b range_e57587c42b9f range_347039695a9a range_8ffb51658e47 range_66118a405c41 range_710db081e225 range_f3820211525c range_867084521367 range_99b97d20ce16 range_1d2dabdc3a1d range_30a6f1a9d664 range_cf8d0e331932 range_c738b5f32166 range_f3bd27945891 range_4ed743629973 range_0fc119685f77 range_06ac0b8d208f range_9d4728877e7c range_da3a4fdda6ef range_6bbcadf218a7 range_00cb3b4feb9a range_1b36257e7689 range_ac104a6223c1 range_813517c9c8c1 range_bb9e0bf9cc0e range_2cb1bee0f8c3 range_0557e1632198 range_a9f793d41229 range_debf8d0a4b8d range_bed0a0717d80 range_43d6f964c324 range_e2ff55ee097d range_b38443b376d4 range_f1c15d07a1de range_c3b6b25c5cf1 range_c8cb3d26ef6b range_170b8f965357 range_0ab60610b16e range_5dd0c8701361 range_ce269f356483 range_2e7af262b199 range_c7dfb10adc6d range_e405239f658e range_335cfc4dac49 range_f0f3411e5b75 range_6fdf894f31d7 range_c17818be1785 range_3705762df72c range_c8449d3d9989 range_32044720a21a range_e7072369f60c range_22708fc8ccbc
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 14.29% 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
      Title check✅ PassedThe PR title directly summarizes the main changes: a performance rewrite of virtual-core focusing on mount/measure optimizations, iOS Safari handling, and scroll restoration features.
      Description check✅ PassedThe PR description comprehensively covers all template sections: detailed change summary with six changesets, benchmark metrics, bundle-size impact, behavior changes, new features, test coverage improvements, and a clear test plan with checkmarks.
      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.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing Touches
      📝 Generate docstrings
      • Create stacked PR
      • Commit on current branch
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `taren/brave-wing-8c454f`

      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. github-actions[bot](GitHub profile, opens in a new tab)commented

      🚀 Changeset Version Preview

      2 package(s) bumped directly, 6 bumped as dependents.

      🟨 Minor bumps

      PackageVersionReason
      @tanstack/virtual-core3.14.0 → 3.15.0Changeset

      🟩 Patch bumps

      PackageVersionReason
      @tanstack/react-virtual3.13.24 → 3.13.25Changeset
      @tanstack/angular-virtual5.0.0 → 5.0.1Dependent
      @tanstack/lit-virtual3.13.25 → 3.13.26Dependent
      @tanstack/solid-virtual3.13.24 → 3.13.25Dependent
      @tanstack/svelte-virtual3.13.24 → 3.13.25Dependent
      @tanstack/virtual-benchmarks0.0.0 → 0.0.1Dependent
      @tanstack/vue-virtual3.13.24 → 3.13.25Dependent
    3. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 186b3bd60dd1f050270ca62ecfc7d968f79e3a11

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded2m 31sView ↗
      nx run-many --target=build --exclude=examples/**✅ Succeeded16sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-05-20 19:16:47 UTC

    4. socket-security[bot](GitHub profile, opens in a new tab)commented

      Review the following changes in direct dependencies. Learn more about Socket for GitHub.

      Diff Package Supply Chain
      Security
      Vulnerability Quality Maintenance License
      Addedreact-window@​2.2.79910010088100
      Addedvirtua@​0.49.19910010091100
      Addedreact-virtuoso@​4.18.710010010094100

      View full report

    5. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented
      More templates

      @tanstack/angular-virtual

      npm i https://pkg.pr.new/@tanstack/angular-virtual@1168

      @tanstack/lit-virtual

      npm i https://pkg.pr.new/@tanstack/lit-virtual@1168

      @tanstack/react-virtual

      npm i https://pkg.pr.new/@tanstack/react-virtual@1168

      @tanstack/solid-virtual

      npm i https://pkg.pr.new/@tanstack/solid-virtual@1168

      @tanstack/svelte-virtual

      npm i https://pkg.pr.new/@tanstack/svelte-virtual@1168

      @tanstack/virtual-core

      npm i https://pkg.pr.new/@tanstack/virtual-core@1168

      @tanstack/vue-virtual

      npm i https://pkg.pr.new/@tanstack/vue-virtual@1168

      commit: 186b3bd

    6. Actionable comments posted: 11

      Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (2)
      packages/virtual-core/tests/index.test.ts (1)

      50-60: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

      Restore global ResizeObserver after this test.

      This mutates global state without cleanup, which can leak into later tests and create order-dependent failures.

      Suggested fix
      -  global.ResizeObserver = mockResizeObserver as any
      +  const prevResizeObserver = global.ResizeObserver
      +  global.ResizeObserver = mockResizeObserver as any
      +  try {
      +    // ...existing test body...
      +  } finally {
      +    global.ResizeObserver = prevResizeObserver
      +  }
      🤖 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/virtual-core/tests/index.test.ts` around lines 50 - 60, Save the
      original global.ResizeObserver before you replace it and restore it after the
      test: capture const originalResizeObserver = global.ResizeObserver at top of the
      test file, assign global.ResizeObserver = mockResizeObserver for the test (using
      the existing mockResizeObserver and resizeCallback variables), and add an
      afterEach (or finally block) that sets global.ResizeObserver =
      originalResizeObserver to ensure the global is restored; reference the mock
      variable names mockResizeObserver, resizeCallback and global.ResizeObserver to
      locate where to add the save/restore and the cleanup hook.
      packages/virtual-core/src/index.ts (1)

      540-551: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

      Reset transient iOS state on touchcancel and teardown.

      This touch lifecycle can get stuck. A gesture may end via touchcancel, and cleanup() currently leaves _iosTouching / _iosJustTouchEnded / _iosDeferredAdjustment alive. From there _flushIosDeferredIfReady() keeps bailing out, or a deferred delta can leak into the next mounted scroll element.

      Suggested fix
      +  private _resetIosTransientState = () => {
      +    this._iosTouching = false
      +    this._iosJustTouchEnded = false
      +    this._iosDeferredAdjustment = 0
      +    this._intendedScrollOffset = null
      +    if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {
      +      this.targetWindow.clearTimeout(this._iosTouchEndTimerId)
      +      this._iosTouchEndTimerId = null
      +    }
      +  }
      +
         private cleanup = () => {
           this.unsubs.filter(Boolean).forEach((d) => d!())
           this.unsubs = []
           this.observer.disconnect()
      +    this._resetIosTransientState()
           if (this.rafId != null && this.targetWindow) {
             this.targetWindow.cancelAnimationFrame(this.rafId)
             this.rafId = null
           }
      @@
               const onTouchEnd = () => {
                 this._iosTouching = false
      @@
                 }, 150)
               }
      +        const onTouchCancel = () => {
      +          this._resetIosTransientState()
      +        }
               scrollEl.addEventListener(
                 'touchstart',
                 onTouchStart,
                 addEventListenerOptions,
               )
               scrollEl.addEventListener(
                 'touchend',
                 onTouchEnd,
                 addEventListenerOptions,
               )
      +        scrollEl.addEventListener(
      +          'touchcancel',
      +          onTouchCancel,
      +          addEventListenerOptions,
      +        )
               this.unsubs.push(() => {
                 scrollEl.removeEventListener('touchstart', onTouchStart)
                 scrollEl.removeEventListener('touchend', onTouchEnd)
      -          if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {
      -            this.targetWindow.clearTimeout(this._iosTouchEndTimerId)
      -            this._iosTouchEndTimerId = null
      -          }
      +          scrollEl.removeEventListener('touchcancel', onTouchCancel)
               })

      Also applies to: 629-677, 690-694

      🤖 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/virtual-core/src/index.ts` around lines 540 - 551, Reset the
      transient iOS touch state (_iosTouching, _iosJustTouchEnded,
      _iosDeferredAdjustment) both when handling touchcancel and during teardown; in
      the touchcancel handler (where touchend/touchstart logic lives) ensure those
      three private flags are cleared and any pending deferred delta is discarded, and
      update the cleanup method (cleanup) to also set _iosTouching = false,
      _iosJustTouchEnded = false, and _iosDeferredAdjustment = null so
      _flushIosDeferredIfReady cannot bail out or leak a delta into the next mount.
      Reference the existing _flushIosDeferredIfReady logic and the touch event
      handlers to locate where to clear these fields.
      🧹 Nitpick comments (1)
      benchmarks/src/lib/harness.ts (1)

      17-19: ⚡ Quick win

      Align isFullyMeasured contract with the wait-dynamic-measure implementation.

      The interface/docs say this callback is used for wait-dynamic-measure, but the action currently ignores it and only checks total-size stability. That makes page-level implementations dead and can skew convergence timing.

      ♻️ Suggested change
             } else if (scenario.action === 'wait-dynamic-measure') {
      @@
               while (stableCount < 8 && performance.now() - t0 < 3000) {
                 await nextFrame()
                 const cur = h.getTotalSize()
      -          if (cur === lastTotal && cur > 0) stableCount++
      +          const sizeStable = cur === lastTotal && cur > 0
      +          const fullyMeasured = h.isFullyMeasured ? h.isFullyMeasured() : true
      +          if (sizeStable && fullyMeasured) stableCount++
                 else stableCount = 0
                 lastTotal = cur
               }
               actionMs = performance.now() - t0
             }

      Also applies to: 282-297

      🤖 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 `@benchmarks/src/lib/harness.ts` around lines 17 - 19, The wait-dynamic-measure
      action currently only checks total-size stability and ignores the optional
      isFullyMeasured callback, so update the wait-dynamic-measure polling logic to
      call isFullyMeasured() (when present) and require it to return true before
      treating measurement as converged; keep using the existing total-size/stability
      checks but combine them with isFullyMeasured() so page-level implementations are
      respected. Locate the polling loop in the wait-dynamic-measure action and add a
      conditional that invokes props.isFullyMeasured() (or the interface’s
      isFullyMeasured) each poll and only resolve when both size stability and
      isFullyMeasured() (if provided) are satisfied. Ensure the isFullyMeasured
      signature in the harness/interface remains unchanged.
      🤖 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 `@benchmarks/README.md`:
      - Around line 31-45: The fenced tree block in benchmarks/README.md is missing a
      language hint which triggers MD040 lint errors; update the opening fence for the
      ASCII tree (the block that starts with ``` on the tree showing benchmarks/ ├──
      src/ ...) to include a language token such as text (i.e. change the fence from
      ``` to ```text) so the markdown linter recognizes it as a plain-text code block;
      locate the fenced block in README.md (the directory tree block) and only modify
      the opening fence to include the language hint.
      - Line 162: Update the fairness note that incorrectly mentions "React 19" to
      match the package's declared React version (e.g., React ^18.3.1); locate the
      sentence "React 19 runs in production mode (no `<StrictMode>`)" in
      benchmarks/README.md and replace it with a corrected statement such as "React 18
      (package declares ^18.3.1) runs in production mode (no `<StrictMode>`)" so the
      methodology accurately reflects the actual React version used.
      
      In `@benchmarks/runner/run.mjs`:
      - Around line 81-103: The runner currently persists only scenario.id into
      results, losing fields like count, itemSize, dynamic, and action and violating
      the shared ScenarioResult contract; in runScenario locate where the local
      variable scenario (from import '/src/scenarios/types.ts' and
      mod.SCENARIOS.find(...)) and the returned result from window.bench.run(scenario)
      are assembled, and change the code to include and persist the full scenario
      object (merge or attach the complete scenario properties onto the returned
      result) so the stored ScenarioResult contains the full scenario shape rather
      than only { id }.
      - Around line 282-290: The error-path metrics object omits the landingErrorPx
      field so failed-run rows have a different schema; update the failure/exception
      branch that builds the metrics object (the metrics literal) to include
      landingErrorPx with a null (or the same sentinel used elsewhere) so every
      metrics object (success and error paths) contains landingErrorPx.
      - Around line 90-93: The browser-side dynamic import in page.evaluate currently
      uses the source path '/src/scenarios/types.ts' which will fail in Vite preview;
      change the import to load the built module or a file served from public (e.g.,
      import the compiled scenarios module from the dist/public path or expose a JSON
      module) when resolving SCENARIOS inside page.evaluate, and ensure you reference
      mod.SCENARIOS and scenario by id as before. Also fix the payloads where only {
      id: scenarioId } is persisted (variables around scenarioId / ScenarioInput) to
      include the full ScenarioInput fields (count, itemSize, dynamic, action) so runs
      are reproducible, and when constructing error result objects (ScenarioMetrics),
      include the required landingErrorPx field so error and success metric shapes
      match.
      
      In `@benchmarks/src/lib/dataset.ts`:
      - Line 57: Replace the bracket-style array type annotations (e.g. Item[],
      string[], etc.) in this file with the generic Array<T> form to satisfy
      `@typescript-eslint/array-type`; specifically update the return type currently
      written as Item[] and the other three similar occurrences to Array<Item> (or the
      appropriate Array<...> for their element types) so all four array type
      annotations use Array<T> consistently.
      
      In `@benchmarks/src/pages/VirtuaPage.tsx`:
      - Around line 38-48: getTotalSize currently queries el but never uses it,
      causing the function to always fall back to firstElementChild/hostRef and
      produce wrong sizes when a different sized node is present; update getTotalSize
      to prefer the discovered element's height by returning el?.scrollHeight (or
      el?.clientHeight/offsetHeight if appropriate) before falling back to
      (hostRef.current?.firstElementChild as HTMLElement | null)?.scrollHeight, then
      hostRef.current?.scrollHeight, and finally 0—modify the return expression in the
      getTotalSize function to use el first.
      
      In `@benchmarks/src/scenarios/types.ts`:
      - Line 59: The exported SCENARIOS constant is declared with the bracket array
      syntax which violates the `@typescript-eslint/array-type` rule; change its type
      annotation from ScenarioInput[] to Array<ScenarioInput> (i.e., update the
      declaration of SCENARIOS in types.ts to use Array<ScenarioInput>) so the export
      satisfies the configured ESLint rule while preserving the existing value.
      
      In `@packages/virtual-core/src/index.ts`:
      - Around line 703-708: The deferred iOS flush uses this._iosDeferredAdjustment
      and calls this._scrollToOffset(cur, { adjustments: delta, ... }) but fails to
      update the running accumulator this.scrollAdjustments; change the flush path so
      after computing delta you also add it into this.scrollAdjustments (i.e.,
      this.scrollAdjustments += delta) before calling _scrollToOffset, and apply the
      same change to the other deferred-flush site around the 1318-1321 region so
      subsequent resize calculations use the updated accumulator rather than a stale
      offset.
      - Around line 1618-1622: measure() currently clears itemSizeCache and
      laneAssignments but does not reset pendingMin or measurementsCache, so stale
      measurements can persist; update measure() to also reset pendingMin (set to its
      initial "no pending" state) and clear or reinitialize measurementsCache so the
      next getMeasurements() rebuilds from scratch; keep the existing increments to
      itemSizeCacheVersion and the notify(false) call and reference the same symbols
      (measure(), pendingMin, measurementsCache, itemSizeCache, laneAssignments,
      itemSizeCacheVersion, notify(false)) when making the change.
      
      In `@packages/virtual-core/tests/index.test.ts`:
      - Around line 1323-1337: The test uses a wall-clock assertion
      (expect(elapsed).toBeLessThan(50)) which is flaky; remove the timing check and
      replace it with a deterministic assertion: after constructing the Virtualizer
      and calling v['getMeasurements'](), assert that the returned/internal
      measurements are a typed numeric buffer (e.g., instance of a TypedArray) or that
      measurements.length === 1_000_000 and elements are primitive numbers (typeof
      measurements[0] !== 'object'), so the test verifies no per-item object
      allocations without relying on elapsed time; reference Virtualizer and its
      getMeasurements() call to locate the code to change.
      
      ---
      
      Outside diff comments:
      In `@packages/virtual-core/src/index.ts`:
      - Around line 540-551: Reset the transient iOS touch state (_iosTouching,
      _iosJustTouchEnded, _iosDeferredAdjustment) both when handling touchcancel and
      during teardown; in the touchcancel handler (where touchend/touchstart logic
      lives) ensure those three private flags are cleared and any pending deferred
      delta is discarded, and update the cleanup method (cleanup) to also set
      _iosTouching = false, _iosJustTouchEnded = false, and _iosDeferredAdjustment =
      null so _flushIosDeferredIfReady cannot bail out or leak a delta into the next
      mount. Reference the existing _flushIosDeferredIfReady logic and the touch event
      handlers to locate where to clear these fields.
      
      In `@packages/virtual-core/tests/index.test.ts`:
      - Around line 50-60: Save the original global.ResizeObserver before you replace
      it and restore it after the test: capture const originalResizeObserver =
      global.ResizeObserver at top of the test file, assign global.ResizeObserver =
      mockResizeObserver for the test (using the existing mockResizeObserver and
      resizeCallback variables), and add an afterEach (or finally block) that sets
      global.ResizeObserver = originalResizeObserver to ensure the global is restored;
      reference the mock variable names mockResizeObserver, resizeCallback and
      global.ResizeObserver to locate where to add the save/restore and the cleanup
      hook.
      
      ---
      
      Nitpick comments:
      In `@benchmarks/src/lib/harness.ts`:
      - Around line 17-19: The wait-dynamic-measure action currently only checks
      total-size stability and ignores the optional isFullyMeasured callback, so
      update the wait-dynamic-measure polling logic to call isFullyMeasured() (when
      present) and require it to return true before treating measurement as converged;
      keep using the existing total-size/stability checks but combine them with
      isFullyMeasured() so page-level implementations are respected. Locate the
      polling loop in the wait-dynamic-measure action and add a conditional that
      invokes props.isFullyMeasured() (or the interface’s isFullyMeasured) each poll
      and only resolve when both size stability and isFullyMeasured() (if provided)
      are satisfied. Ensure the isFullyMeasured signature in the harness/interface
      remains unchanged.
      🪄 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

      Run ID: 509f8de1-0816-46d5-ac23-3e56ddb65611

      📥 Commits

      Reviewing files that changed from the base of the PR and between b9feeb63421e78c6ad3192dc82ee9a0f3d74d1eb and c09bcab51245db5384fe842517644b27ada7cdf2.

      ⛔ Files ignored due to path filters (2)
      • .claude/scheduled_tasks.lock is excluded by !**/*.lock
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (32)
      • .changeset/feat-core-ios-scroll-handling.md
      • .changeset/feat-core-scroll-to-index-smooth.md
      • .changeset/feat-core-scroll-up-jank-default.md
      • .changeset/feat-core-take-snapshot.md
      • .changeset/perf-core-mount-and-measure-storm.md
      • .changeset/perf-react-virtual-rerender-alloc.md
      • benchmarks/.gitignore
      • benchmarks/README.md
      • benchmarks/index.html
      • benchmarks/package.json
      • benchmarks/results/.gitkeep
      • benchmarks/results/SAMPLE.json
      • benchmarks/runner/run.mjs
      • benchmarks/src/lib/dataset.ts
      • benchmarks/src/lib/harness.ts
      • benchmarks/src/main.tsx
      • benchmarks/src/pages/TanstackPage.tsx
      • benchmarks/src/pages/VirtuaPage.tsx
      • benchmarks/src/pages/VirtuosoPage.tsx
      • benchmarks/src/pages/WindowPage.tsx
      • benchmarks/src/scenarios/types.ts
      • benchmarks/tsconfig.json
      • benchmarks/vite.config.ts
      • docs/api/virtualizer.md
      • knip.json
      • packages/react-virtual/src/index.tsx
      • packages/virtual-core/src/index.ts
      • packages/virtual-core/src/lazy-measurements.ts
      • packages/virtual-core/src/utils.ts
      • packages/virtual-core/tests/bench.bench.ts
      • packages/virtual-core/tests/index.test.ts
      • pnpm-workspace.yaml
      @@ -1316,10 +1609,14 @@
      13161609 behavior: ScrollBehavior | undefined
      13171610 },
      13181611 ) => {
      1612+ // Record the intended logical scroll target so the next scroll event
      1613+ // can reconcile against subpixel rounding by the browser.
      1614+ this._intendedScrollOffset = offset + (adjustments ?? 0)
      13191615 this.options.scrollToFn(offset, { behavior, adjustments }, this)
      13201616 }
      13211617
      13221618 measure = () => {
      1323- this.itemSizeCache = new Map()
      1324- this.laneAssignments = new Map() // Clear lane cache for full re-layout
      1619+ this.itemSizeCache.clear()
      1620+ this.laneAssignments.clear() // Clear lane cache for full re-layout
      1621+ this.itemSizeCacheVersion++
      13251622 this.notify(false)
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

      Force measure() to invalidate the full layout.

      measure() clears itemSizeCache, but it never resets pendingMin or measurementsCache. If a prior resizeItem() already dirtied some later index, the next getMeasurements() rebuild will preserve stale entries before that point, so measure() does not reliably clear all cached measurements.

      Suggested fix
         measure = () => {
      +    this.pendingMin = 0
      +    this.measurementsCache = []
           this.itemSizeCache.clear()
           this.laneAssignments.clear() // Clear lane cache for full re-layout
           this.itemSizeCacheVersion++
           this.notify(false)
         }
      📝 Committable suggestion

      ‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      Suggested change
      1626+ measure = () => {
      1627+ this.pendingMin = 0
      1628+ this.measurementsCache = []
      1629+ this.itemSizeCache.clear()
      1630+ this.laneAssignments.clear() // Clear lane cache for full re-layout
      1631+ this.itemSizeCacheVersion++
      1632+ this.notify(false)
      🤖 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/virtual-core/src/index.ts` around lines 1618 - 1622, measure()
      currently clears itemSizeCache and laneAssignments but does not reset pendingMin
      or measurementsCache, so stale measurements can persist; update measure() to
      also reset pendingMin (set to its initial "no pending" state) and clear or
      reinitialize measurementsCache so the next getMeasurements() rebuilds from
      scratch; keep the existing increments to itemSizeCacheVersion and the
      notify(false) call and reference the same symbols (measure(), pendingMin,
      measurementsCache, itemSizeCache, laneAssignments, itemSizeCacheVersion,
      notify(false)) when making the change.
    7. SeanCassiere reviewed

      @@ -0,0 +1 @@
      1+{"sessionId":"e402bf71-ca74-4aa5-856c-da0c2053caab","pid":78596,"procStart":"Sat May 16 20:13:35 2026","acquiredAt":1779000018499}
      SeanCassierecommented

      Kill?

    8. piecyk approved these changes

      LGTM 👍 Impressive rewrite. The core perf wins are well-motivated and clearly implemented, let's 🚢 🇮🇹

      @@ -1,3 +1,17 @@
      1+import { createLazyMeasurementsView } from './lazy-measurements'
      12 import { approxEqual, debounce, memo, notUndefined } from './utils'
      23
      3-export * from './utils'
      4+// Browser-aware iOS detection. Programmatic `scrollTo`/`scrollTop` writes
      5+// during a momentum-scroll cancel the momentum on iOS WebKit, so we defer
      6+// scroll-position adjustments triggered by mid-scroll resizes until the
      7+// scroll settles. SSR-safe (returns false when navigator is unavailable).
      8+let _isIOSResult: boolean | undefined
      9+const isIOSWebKit = (): boolean => {
      10+ if (_isIOSResult !== undefined) return _isIOSResult
      11+ if (typeof navigator === 'undefined') return (_isIOSResult = false)
      12+ if (/iP(hone|od|ad)/.test(navigator.userAgent)) return (_isIOSResult = true)
      13+ // iPadOS 13+ reports as MacIntel; touch-points distinguishes it from desktop.
      14+ const mtp = (navigator as Navigator & { maxTouchPoints?: number })
      15+ .maxTouchPoints
      16+ return (_isIOSResult =
      17+ navigator.platform === 'MacIntel' && mtp !== undefined && mtp > 0)
      piecykcommented

      Looks like navigator.platform is deprecated. It still works today, but could be replaced with navigator.userAgentData?.platform with a fallback.

        const nav = navigator as Navigator & {
          userAgentData?: {
            platform?: string
          }
          maxTouchPoints?: number
        }
      
        if (/\b(iPhone|iPod|iPad)\b/.test(nav.userAgent)) {
          return (_isIOSResult = true)
        }
      
        // iPadOS 13+ may report as macOS/MacIntel; touch-points distinguish it from desktop.
        // Use userAgentData.platform when available, otherwise fall back to navigator.platform.
        const platform = nav.userAgentData?.platform ?? nav.platform
        const maxTouchPoints = nav.maxTouchPoints ?? 0
      
        return (_isIOSResult =
          (platform === 'macOS' || platform === 'MacIntel') && maxTouchPoints > 0)```
      KevinVandycommented

      I had a couple iterations of safely accessing navigator.platform in all environments safely (like even cloudflare ssr stuff) and I ended up at this util in hotkeys https://github.com/TanStack/hotkeys/blob/404666b65dbec31d47da1be4c2a2210e7e53a615/packages/hotkeys/src/constants.ts#L26

    9. tannerlinsley merged this99355ad

    10. tannerlinsley closed this

Sign in to join this conversation.