Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

perf(react-router): share one IntersectionObserver per router for viewport preloading - #9001

Open
schiller-manuel wants to merge 1 commit into
schiller-manuel-perf-shared-viewport-observerfrom
schiller-manuel-perf-shared-viewport-observer-x6
Open

schiller-manuel wants to merge 1 commit into
schiller-manuel-perf-shared-viewport-observerfrom
schiller-manuel-perf-shared-viewport-observer-x6

Conversation

@schiller-manuel

@schiller-manuel schiller-manuel commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 95c7c4e452ccd5c21af84740c33c186eb95b358e

Dimension Assessment Rationale
Change confidence 8/10 ↑ react-router test:unit, test:types and test:eslint pass.
↑ New per-target routing test fails on the old per-Link code.
↑ link-viewport asserts one observe and one release per Link.
↓ One intended behavior change: a leave + re-enter in one batch now restarts preloadDelay.
↓ No e2e run; CI pending.
Performance evidence 5/10 ↑ Chromium lab: viewport Link mount −17 to −18% (12 rounds, both preload configs).
↓ link-viewport (jsdom) shows no significant change.
↓ Lab numbers come from a separate harness, not from CI.
Bundle size 4/10 ↓ gzip +7 to +26 B on every React scenario (+14 B on react-router.minimal), a known exception to the net-zero goal.
↑ Solid and Vue are unchanged.

Stacked on #8998 (adds the link-viewport client-nav scenario). Review that PR first.

AI-assisted: written with GitHub Copilot, reviewed by the author.

🎯 Changes

Before this change, every <Link preload="viewport"> created its own IntersectionObserver. Now each router has one, stored in router.stores._linkObserver next to _linkScopes, and never in a module-level singleton. A module WeakMap<Element, handler> routes each entry to its Link's handler:

observer = router.stores._linkObserver ??= new IntersectionObserver(
  (entries) => entries.forEach((entry) => viewportHandlers.get(entry.target)?.(entry)),
  { rootMargin: '100px' },
)
viewportHandlers.set(element, enqueuePreload)
observer.observe(element)
// cleanup
viewportHandlers.delete(element) // also drops notifications queued before unobserve
observer?.unobserve(element)
  • Each entry is handled in order, so there is no "latest entry per target" map. Running enqueuePreload and cancelPreload in sequence ends in the same state as running only the last entry, with one exception: a leave + re-enter within one batch now restarts preloadDelay. The old code kept the existing timer. The test covers both cases.
  • To reduce the size cost, I also simplified useStableValues, removed the stable innerRef from the hook deps, and made enqueuePreload's entry parameter required, since entries.pop() no longer passes undefined.
  • Tests:
    • Two tests that asserted one observer per Link (disconnect counts, a new observer callback after a destination change) now assert unobserve.
    • One new test checks that the shared observer preloads only the Link whose element intersected.

Performance

Motivating evidence (Chromium lab). A production bundle mounts and unmounts 1,000 <Link preload="viewport"> under RouterProvider in Chromium. Results are from 12 interleaved rounds against the unpatched base, with an A/A control:

Workload defaultPreload A/A X6
mountViewport 'intent' −0.1% −18.4%
mountViewport false −0.5% −16.8%
mountSimple / mountParams / leaveBlur / hover both within ±1.4% within ±1.3% (no effect)

link-viewport client-nav scenario (#8998): no significant change. jsdom has no IntersectionObserver, so the scenario installs a stub whose constructor does almost nothing. That removes the native per-observer cost this change saves, so CI cannot show the improvement. These are local React runs on #8998's head (d9ea339), alternating baseline and candidate, in hz (higher is better):

Mode Baseline (5 runs) X6 (5 runs) Δ mean Baseline spread
CodSpeed simulation flags 167.7 / 174.1 / 173.4 / 172.3 / 175.5 (mean 172.6) 167.4 / 172.4 / 175.8 / 170.6 / 169.9 (mean 171.2) −0.8% 4.6%
walltime 262.7 / 251.6 / 216.3 / 209.9 / 232.6 (mean 234.6) 247.1 / 227.4 / 227.4 / 209.2 / 231.1 (mean 228.4) −2.6% 25%

Both differences are well inside the baseline's own run-to-run spread. Solid and Vue are unchanged by this PR; their controls were 94.1 and 82.9 hz.

Bundle size (gzip bytes vs. #8998)

Known exception to the net-zero goal: gzip grows by a few bytes on every React scenario.

Scenario Δ gzip
react-router.minimal +14
react-router.full +14
react-start.minimal +26
react-start.full +19
react-start.deferred-hydration +26
react-start.query-integration +8
react-start.rsbuild.minimal +7
react-start.rsbuild.minimal-iife +7
react-start.rsbuild.full +13
solid-* / vue-* 0

Alternatives I measured that were larger or no better:

  • a router-keyed WeakMap to the observer: +18 B
  • [observer, Map]: +47 B
  • one WeakMap for both roles: +7 to +19 B
  • deduplicating Route/RootRoute members: −345 raw bytes, but no gzip gain

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested code changes locally with the relevant test commands, or tests do not apply to this pull request.
    • CI=1 NX_DAEMON=false pnpm nx run-many -p @tanstack/react-router -t test:unit test:types test:eslint --skipRemoteCache: passed
    • pnpm benchmark:bundle-size:run --baseline <#8998 baseline>: deltas above
    • link-viewport React/Solid/Vue via vitest bench --mode benchmark: numbers above
  • I fully understand the code in this pull request, including any code generated with AI assistance.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • Bug Fixes
    • Viewport-based link preloading now targets links that enter the viewport, rather than preloading links that are not visible.
    • The preload delay restarts when a link leaves and re-enters the viewport within the same observer update.
    • Links are no longer observed after they are removed, and pending preload timers are canceled during cleanup.
    • Link option changes no longer require replacing the viewport observer callback.

@changeset-bot

changeset-bot Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 95c7c4e

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 5 packages
Name Type
@tanstack/react-router Patch
@tanstack/react-start-client Patch
@tanstack/react-start-rsc Patch
@tanstack/react-start-server Patch
@tanstack/react-start Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Viewport-preloaded links now share one IntersectionObserver per router. The observer dispatches entries to handlers for individual links. Cleanup removes each link’s handler, unobserves its element, and cancels pending timers.

Changes: Viewport preload observer

Layer / File(s) Summary
Shared observer registration and dispatch
packages/react-router/src/matchContext.tsx, packages/react-router/src/link.tsx, packages/react-router/tests/link.test.tsx, packages/react-router/tests/utils.ts, .changeset/shared-viewport-observer.md
The router stores the shared observer. Link effects register elements and handlers, and cleanup removes handlers, unobserves elements, and cancels timers. Tests cover cleanup, delay restart, and selective preloading. The changeset declares a patch for @tanstack/react-router.

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

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant LinkEffect
  participant RouterStores
  participant IntersectionObserver
  participant viewportHandlers
  participant RouterPreload
  LinkEffect->>RouterStores: Register element with shared observer
  RouterStores->>IntersectionObserver: Observe element
  IntersectionObserver->>viewportHandlers: Dispatch entry for target
  viewportHandlers->>RouterPreload: Preload intersecting link
  LinkEffect->>IntersectionObserver: Unobserve element on cleanup
Loading

Possibly related PRs

Merge Risk: Minimal · up to 95c7c

Viewport-preloaded links now share one observer per router, which reduces mount cost. No merge-blocking issue was found; at worst a rare spurious prefetch could occur when a link's destination changes in the same batch as a notification.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: viewport preloading in React Router now shares one IntersectionObserver per router instead of creating one per Link. The raw summary and objectives confirm this is the…
Description check Passed The description follows the template's sections: Changes, Checklist, and Release Impact. It explains the shared observer design, the behavior change for leave and re-enter within one batch, the relate…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: viewport preloading in React Router now shares one IntersectionObserver per router instead of creating one per Link. The raw summary and objectives confirm this is the core change. The perf(...) prefix follows conventional commit style.

Full details: Description check

Explanation

The description follows the template's sections: Changes, Checklist, and Release Impact. It explains the shared observer design, the behavior change for leave and re-enter within one batch, the related simplifications, and the tests. It includes performance and bundle-size evidence and discloses AI assistance. The final checklist item ('I fully understand the code...') is unchecked, and the template's release-impact box is checked. Those are author-side items that a reviewer should confirm. The description also depends on PR #8998 for review context, which is noted.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 25a81fa and 95c7c4e.

Files selected for processing: 5

  • .changeset/shared-viewport-observer.md
  • packages/react-router/src/link.tsx
  • packages/react-router/src/matchContext.tsx
  • packages/react-router/tests/link.test.tsx
  • packages/react-router/tests/utils.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

@nx-cloud

nx-cloud Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

View your CI Pipeline Execution ↗ for commit 95c7c4e

Command Status Duration Result
nx affected --targets=test:eslint,test:unit,tes... ✅ Succeeded 8m 41s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1m 19s View ↗

💡 With Ultracache enabled, Nx Cloud learns each task's file inputs in CI and uses them on later runs. Turn on Ultracache in workspace settings ↗ · Read docs ↗


☁️ Nx Cloud last updated this comment at 2026-11-27 14:23:25 UTC

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Changeset Version Preview

1 package(s) bumped directly, 4 bumped as dependents.

🟩 Patch bumps

Package Version Reason
@tanstack/react-router 1.170.46 → 1.170.47 Changeset
@tanstack/react-start 1.169.7 → 1.169.8 Dependent
@tanstack/react-start-client 1.168.45 → 1.168.46 Dependent
@tanstack/react-start-rsc 0.1.68 → 0.1.69 Dependent
@tanstack/react-start-server 1.167.52 → 1.167.53 Dependent

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Bundle Size Benchmarks

  • Commit: 22b74316a92d
  • Measured at: 2026-11-27T14:15:23.525Z
  • Baseline source: history:10b22c276ea7
  • Dashboard: bundle-size history

The following scenarios have bundle-size changes compared with the baseline:

Scenario Current (gzip) Initial (gzip) Raw Brotli Trend
react-router.minimal 84.1 KiB
+14 B
83.9 KiB
+16 B
261.6 KiB
+61 B
73.3 KiB
+29 B
▁▁▁▁▁▁▁▅▅▅▅█
react-router.full 87.6 KiB
+14 B
87.5 KiB
+11 B
273.5 KiB
+53 B
76.4 KiB
-26 B
▁▁▁▁▁▁▁▅▅▅▅█
react-start.minimal 96.8 KiB
+26 B
96.7 KiB
+26 B
302.5 KiB
+54 B
84.0 KiB
-104 B
▁▁▁▁▁▁▁▃▃▃▃█
react-start.query-integration 104.2 KiB
+8 B
104.1 KiB
+8 B
329.1 KiB
+53 B
90.5 KiB
+33 B
▂▂▂▂▂▁▁▅▅▅▅█
react-start.deferred-hydration 97.5 KiB
+26 B
96.7 KiB
+25 B
303.9 KiB
+54 B
84.8 KiB
+8 B
▁▁▁▁▁▁▁▅▅▅▅█
react-start.full 99.9 KiB
+19 B
99.7 KiB
+17 B
311.8 KiB
+57 B
86.7 KiB
-11 B
▁▁▁▁▁▁▁▄▄▄▄█
react-start.rsbuild.minimal 96.7 KiB
+7 B
96.5 KiB
+7 B
298.3 KiB
+56 B
83.5 KiB
+33 B
██▁▁▁▁▁▁▁▁▁▁
react-start.rsbuild.minimal-iife 97.1 KiB
+7 B
96.9 KiB
+7 B
299.3 KiB
+56 B
83.8 KiB
-16 B
██▁▁▁▁▁▁▁▁▁▁
react-start.rsbuild.full 100.0 KiB
+13 B
99.8 KiB
+13 B
308.0 KiB
+56 B
86.2 KiB
+167 B
██▁▁▁▁▁▁▁▁▁▁

Current gzip tracks all emitted client JS chunks. Initial gzip tracks only the entry/import graph. Trend sparkline is historical current gzip ending with this PR measurement; lower is better.

@pkg-pr-new

pkg-pr-new Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
More templates

@tanstack/arktype-adapter

npm i https://pkg.pr.new/@tanstack/arktype-adapter@9001

@tanstack/eslint-plugin-router

npm i https://pkg.pr.new/@tanstack/eslint-plugin-router@9001

@tanstack/eslint-plugin-start

npm i https://pkg.pr.new/@tanstack/eslint-plugin-start@9001

@tanstack/history

npm i https://pkg.pr.new/@tanstack/history@9001

@tanstack/react-router

npm i https://pkg.pr.new/@tanstack/react-router@9001

@tanstack/react-router-devtools

npm i https://pkg.pr.new/@tanstack/react-router-devtools@9001

@tanstack/react-router-ssr-query

npm i https://pkg.pr.new/@tanstack/react-router-ssr-query@9001

@tanstack/react-start

npm i https://pkg.pr.new/@tanstack/react-start@9001

@tanstack/react-start-client

npm i https://pkg.pr.new/@tanstack/react-start-client@9001

@tanstack/react-start-rsc

npm i https://pkg.pr.new/@tanstack/react-start-rsc@9001

@tanstack/react-start-server

npm i https://pkg.pr.new/@tanstack/react-start-server@9001

@tanstack/router-cli

npm i https://pkg.pr.new/@tanstack/router-cli@9001

@tanstack/router-core

npm i https://pkg.pr.new/@tanstack/router-core@9001

@tanstack/router-devtools

npm i https://pkg.pr.new/@tanstack/router-devtools@9001

@tanstack/router-devtools-core

npm i https://pkg.pr.new/@tanstack/router-devtools-core@9001

@tanstack/router-generator

npm i https://pkg.pr.new/@tanstack/router-generator@9001

@tanstack/router-plugin

npm i https://pkg.pr.new/@tanstack/router-plugin@9001

@tanstack/router-ssr-query-core

npm i https://pkg.pr.new/@tanstack/router-ssr-query-core@9001

@tanstack/router-utils

npm i https://pkg.pr.new/@tanstack/router-utils@9001

@tanstack/router-vite-plugin

npm i https://pkg.pr.new/@tanstack/router-vite-plugin@9001

@tanstack/solid-router

npm i https://pkg.pr.new/@tanstack/solid-router@9001

@tanstack/solid-router-devtools

npm i https://pkg.pr.new/@tanstack/solid-router-devtools@9001

@tanstack/solid-router-ssr-query

npm i https://pkg.pr.new/@tanstack/solid-router-ssr-query@9001

@tanstack/solid-start

npm i https://pkg.pr.new/@tanstack/solid-start@9001

@tanstack/solid-start-client

npm i https://pkg.pr.new/@tanstack/solid-start-client@9001

@tanstack/solid-start-server

npm i https://pkg.pr.new/@tanstack/solid-start-server@9001

@tanstack/start-client-core

npm i https://pkg.pr.new/@tanstack/start-client-core@9001

@tanstack/start-fn-stubs

npm i https://pkg.pr.new/@tanstack/start-fn-stubs@9001

@tanstack/start-plugin-core

npm i https://pkg.pr.new/@tanstack/start-plugin-core@9001

@tanstack/start-server-core

npm i https://pkg.pr.new/@tanstack/start-server-core@9001

@tanstack/start-static-server-functions

npm i https://pkg.pr.new/@tanstack/start-static-server-functions@9001

@tanstack/start-storage-context

npm i https://pkg.pr.new/@tanstack/start-storage-context@9001

@tanstack/valibot-adapter

npm i https://pkg.pr.new/@tanstack/valibot-adapter@9001

@tanstack/virtual-file-routes

npm i https://pkg.pr.new/@tanstack/virtual-file-routes@9001

@tanstack/vue-router

npm i https://pkg.pr.new/@tanstack/vue-router@9001

@tanstack/vue-router-devtools

npm i https://pkg.pr.new/@tanstack/vue-router-devtools@9001

@tanstack/vue-router-ssr-query

npm i https://pkg.pr.new/@tanstack/vue-router-ssr-query@9001

@tanstack/vue-start

npm i https://pkg.pr.new/@tanstack/vue-start@9001

@tanstack/vue-start-client

npm i https://pkg.pr.new/@tanstack/vue-start-client@9001

@tanstack/vue-start-server

npm i https://pkg.pr.new/@tanstack/vue-start-server@9001

@tanstack/zod-adapter

npm i https://pkg.pr.new/@tanstack/zod-adapter@9001

commit: 95c7c4e

…wport preloading

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@schiller-manuel
schiller-manuel force-pushed the schiller-manuel-perf-shared-viewport-observer-x6 branch from 162e78e to 95c7c4e Compare November 27, 2026 14:11
@codspeed

codspeed Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Merging this PR will regress 1 benchmark

2 warnings

⚠️ 68 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚠️ 1 benchmark with a significant change ran on different hardware

Its base and head results were measured on machines with a different CPU, core count or memory, so the change might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

⚡ 1 improved benchmark
❌ 1 regressed benchmark
✅ 201 untouched benchmarks
⏩ 3 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Mode Benchmark BASE HEAD Efficiency
❌ Memory mem client unique-location-churn (react) 75.1 KB 77.9 KB -3.52%
⚡ Memory mem server error-paths redirect (react) 14.2 KB 13.4 KB +5.71%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing schiller-manuel-perf-shared-viewport-observer-x6 (95c7c4e) with schiller-manuel-perf-shared-viewport-observer (25a81fa)

Open in CodSpeed

Footnotes

  1. 3 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants