perf(router-core): hydrate without awaiting code-split component chunks #8577
main fromrefs/pull/8577/head·opened 🎯 Changes#
Supersedes #8484 (moved from my work account).
hydrate() awaits loadRouteChunk() for every committed match before setMatches. RouterClient and StartClient render <Await> on that promise, so the root commits nothing until the whole component closure of the matched routes has downloaded. That includes chrome whose code already sits in the entry chunk, such as a header in the root route. A click on a header <Link> in that window is a native document navigation.
We measured the cost on a production React Start app on @tanstack/router-core@1.171.32. The table shows the root commit time, median of 3 runs, at 4x CPU slowdown with 150 ms RTT and 1.6 Mbps:
| Page | Awaiting chunks | Without the wait |
|---|---|---|
| Home | 4484 ms | 3375 ms |
| Search results | 4969 ms | 3825 ms |
| Detail page | 6237 ms | 3890 ms |
| Login | 3991 ms | 3372 ms |
The route body still waits for its own chunk. The bytes loaded before the commit do not change.
This makes the header interactive while the route's Suspense boundary is still dehydrated. That is the window behind #8198, which #8576 closes, so this PR lands best after #8576.
What changes. hydrate() still starts every chunk load, but now it awaits only the lazy route options that have not merged yet (loadRouteChunk(route, false)). A code-split component is a lazyRouteComponent. If its chunk has not arrived when the adapter renders it, it suspends, and the server HTML stays in place until the chunk arrives:
- React keeps the server HTML of a dehydrated Suspense boundary. The root
Outletalways puts the child match inside one. - Solid:
lazy()keeps the server DOM during hydration and hydrates it when the module arrives. The pending branch oflazyRouteComponentrendered<Loadable />, which added one component level and shifted the hydration keys. It now callsLoadable(props). - Vue hydrates an unresolved
defineAsyncComponentonly once its loader settles (since 3.3). The pending branch oflazyRouteComponentrendered an empty<div>; it now renders an async component. A missing module still reloads once. After that reload, the error now reaches the route's error boundary instead of leaving an empty<div>.
All three adapters behave the same, so _hydrateWithoutComponentChunks is gone. A ssr: 'data-only' route keeps the pending UI it already shows until its chunk arrives, with no mismatch and no new flash.
Lazy route options. A route with a lazyFn (.lazy(), createLazyFileRoute) has no component until its options merge, and would render <Outlet /> in its place. Hydration still waits for those options, but only for the options module. It no longer waits for every component chunk in the lane. Scoping the wait to that route's subtree would need each adapter's Match to suspend on route._lazy; I left that for a follow-up.
Failure path. lazyRouteComponent.preload never rejects in React or Solid. It records the error and throws it on render: a module-not-found error reloads the document once (guarded in sessionStorage), and any other error goes to the route's error boundary. So for code-split components the failure path does not change. A rejected lazyFn is still awaited and still retries from that match. The one change is for a hand-written component with a custom preload: it is no longer awaited before the first render, so a component that depends on it must suspend or handle the pending state in render, and a rejecting preload no longer triggers retryFrom. No adapter's lazyRouteComponent.preload rejects, so a rejecting lazyFn is the only real chunk failure left during hydration. The four public-hydration-contract tests that used a rejecting component preload therefore now use a rejecting lazyFn, with the same assertions.
Commits are ordered so that the tail can be dropped: core narrow lazyFn wait, React tests, Solid, Vue, then the flag removal. Dropping the last one keeps the flag; dropping the last two also leaves Vue as it is today.
Size (min+gzip, compared with main): router-core load-client +10 B (the first version of this PR was +40 B). Solid lazyRouteComponent −2 B. Vue lazyRouteComponent −50 B, but a Vue app that does not already use defineAsyncComponent now bundles it (about +0.8 kB).
Tests. Each hydration test renders on the server, hydrates real markup with a component chunk held pending, and checks that the server HTML and DOM nodes are kept, that the page is interactive once the chunk resolves, and that there are no hydration warnings.
packages/react-router/tests/hydration-component-chunks.test.tsx: a pendinglazyRouteComponent; pendinglazyFnoptions; options that resolve to a pendinglazyRouteComponent.packages/solid-router/tests/hydration/: the same cases for Solid, in a newvitest --mode hydrationrun. Solid hydration needs markup from Solid's server build, soglobalSetuprenders it with the server build and the jsdom tests hydrate it with hydratable client output. It also covers an event that ends hydration before the chunk arrives. These tests fail without the Solid fix withHydration Mismatch.packages/vue-router/tests/hydration-component-chunks.test.tsx: the same cases for Vue, plus a missing chunk during hydration. The hydration tests also pass against Vue 3.3.4.lazyRouteComponent-module-not-found.test.tsxcovers the one-time reload and the error boundary after it.packages/router-core/tests/hydration-component-chunks.test.ts: chunk loads start but are not awaited, lazy options are awaited, and a rejectingpreloadcauses no unhandled rejection.
✅ 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.
- I fully understand the code in this pull request, including any code generated with AI assistance.
Local runs on top of main at 57e126e99d, all exit 0: build, test:unit (for Solid: client, --mode server and --mode hydration), test:eslint, test:types and test:build for @tanstack/router-core, @tanstack/react-router, @tanstack/solid-router, @tanstack/vue-router and @tanstack/react-start-client.
E2E in Chromium against production builds (Start always enables auto code splitting): solid-start/basic 84 passed, vue-start/basic 81 passed, solid-start/deferred-hydration 15 passed, solid-start/selective-ssr all 11 passed, vue-start/selective-ssr 8 passed. In both selective-ssr suites, Playwright then timed out waiting for the web server teardown after the tests had passed. I did not check whether that also happens on main. I did not run the React Start e2e suites.
🚀 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
- Hydration can complete while route component code is still loading, preserving server-rendered content until the component is ready.
- Lazy route options are still loaded before route matches are committed, while component preloads no longer delay the first render.
- Routes remain interactive when hydration finishes before their component code arrives.
- Bug Fixes
- Improved handling of component-loading failures during hydration, including module-not-found errors.
- 1
Sheraff(GitHub profile, opens in a new tab) assignedSheraff
(copied from previous PR)
Could you give me a human-readable TL;DR of this change? If i understand correctly we don't await the chunks during hydration (unless they are explicitly lazy) because they are not required for the hydration (they will simply load later, in render, and cause a suspense)
The failure path you are describing, if i understand correctly, is that we're not catching a failed lazy chunk load during hydration anymore, is that right?
Could you enumerate the setups that are impacted and those that aren't? (stuff like auto code splitting, manual code splitting, custom preload, explicit
.lazy...)it'd be interesting to see if we can apply the same logic to Vue and/or Solid. We don't like to advance 1 adapter and leave the other 2 behind (if there isn't a good reason to). And as a bonus if we can apply this to all 3, we can remove
_hydrateWithoutComponentChunkscompletely.also this is interesting
The wait could later be scoped to that route's subtree
does that make the code much more complex? we're trying not to add too many bytes, but i could see that being quite nice for some apps
Sorry I missed these on #8484. Answers below, and I updated the PR.
Close.
hydrate()still starts every chunk load, but it no longer waits for them before it commits the matches. A component whose chunk hasn't arrived suspends, and the server HTML stays on screen until the chunk lands. The only thing hydration still waits for is a.lazy()route whose options haven't loaded, because without them that route would render<Outlet />. One side effect to know about: the header becomes interactive while the route boundary is still dehydrated. That is the #8198 window that #8576 closes, so #8576 should land first.Not really. The built-in
lazyRouteComponent.preloadnever rejects. It stores the error and throws it on render, where a missing module reloads the page once and any other error goes to the route's error boundary. Sohydrate()never caught those failures before either. What does change is the guarantee for a hand-written component: itspreloadis no longer awaited before the first render, so if it depends on that, it must suspend or handle the pending state in render. A failed.lazy()import still triggers a retry.Here is the breakdown:
Setup Before Now Auto code splitting waits doesn't wait Manual lazyRouteComponentwaits doesn't wait .lazy()/createLazyFileRoutewaits for all chunks waits for its options only Custom preloadwaits, retries on reject starts it, doesn't wait ssr: 'data-only'waits pending UI stays until the chunk arrives (no mismatch) Root route, non-split, ssr: falseno change no change Yes, both work now, so I removed
_hydrateWithoutComponentChunks. Each one is covered by an SSR-then-hydrate test with a held chunk. Solid'slazy()already keeps the server DOM; our wrapper added an extra component level that broke the hydration keys, and that was a one-line fix. Vue's wrapper rendered an empty<div>, so it now usesdefineAsyncComponent, which Vue hydrates only after the chunk loads. The Vue hydration test passes on Vue 3.3.4 and 3.5. The cost is about 0.8 kB gzipped for Vue apps that don't already usedefineAsyncComponent.I did a cheap version: hydration now waits only for the lazy options module, not for every chunk in the lane.
load-clientends up +10 B over main instead of +40 B. Scoping the wait to the route's subtree would need every adapter'sMatchto suspend on the lazy options, and Vue can't suspend on a thrown promise, so I'd leave that for a follow-up.
I pushed:
- Core: hydration waits only for unmerged lazy options.
- Solid and Vue:
lazyRouteComponentkeeps the server HTML while its chunk loads. - SSR-then-hydrate tests for React, Solid and Vue.
_hydrateWithoutComponentChunksremoved.- The commits are ordered core, React, Solid, Vue, flag removal, so the Vue part or the flag removal can be dropped if needed.
The workflows need approval to run, since this is my first PR from this account.
This still merges cleanly into
main. I also checked it together with #8576, which I just rebased: I merged this branch into #8576 at 768bca8b1. With both changes,@tanstack/router-coreand@tanstack/react-routertest:unitexit 0 (3642 and 1244 tests). The #8198 reproducer also exits 0, with 0/6 navigations logging errors and the boundary still dehydrated at every click. Onmainalone, the reproducer fails 3/6.@Sheraff could you approve the workflow runs here too? CI has not run on either PR yet.
Sign in to join this conversation.
Navigate logical layers of code changes, visualize relationships, and explore their blast radius.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Repository: TanStack/router/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
720aaec3-8147-492d-97dd-e003ef34cf73📥 Commits
Reviewing files that changed from the base of the PR and between 2b3b27ccae6a23ee2289122e18c181dbacff8b57 and db2548ea5d98c86b571661ad61f4d61915b6f9a6.
📒 Files selected for processing (14)
.changeset/hydrate-without-component-chunks.mdpackages/react-router/tests/hydration-component-chunks.test.tsxpackages/router-core/src/load-client.tspackages/router-core/tests/hydration-component-chunks.test.tspackages/router-core/tests/public-hydration-contract.test.tspackages/solid-router/package.jsonpackages/solid-router/src/lazyRouteComponent.tsxpackages/solid-router/tests/hydration/hydration-component-chunks.test.tsxpackages/solid-router/tests/hydration/render-on-server.tsxpackages/solid-router/tests/hydration/routes.tsxpackages/solid-router/vite.config.tspackages/vue-router/src/lazyRouteComponent.tsxpackages/vue-router/tests/hydration-component-chunks.test.tsxpackages/vue-router/tests/lazyRouteComponent-module-not-found.test.tsx🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
📝 Walkthrough
Walkthrough#
Hydration no longer waits for route component chunks, but it still waits for unresolved lazy route options. The changes include Router Core loading behavior, React and Solid hydration tests, and Vue lazy-component loading changes and tests.
Changes#
Hydration without component chunks
packages/router-core/src/load-client.ts,packages/router-core/tests/*hydration*,packages/router-core/tests/public-hydration-contract.test.ts,.changeset/hydrate-without-component-chunks.mdpackages/react-router/tests/hydration-component-chunks.test.tsxpackages/solid-router/src/lazyRouteComponent.tsx,packages/solid-router/tests/hydration/*,packages/solid-router/vite.config.ts,packages/solid-router/package.jsonLoadabledirectly. Hydration tests cover pending chunks, lazy route options, and interaction before a chunk resolves. Test setup renders server state and adds a hydration test mode.packages/vue-router/src/lazyRouteComponent.tsx,packages/vue-router/tests/hydration-component-chunks.test.tsx,packages/vue-router/tests/lazyRouteComponent-module-not-found.test.tsxdefineAsyncComponentfor lazy route components and sets a session-storage reload marker for module-not-found errors. Tests cover hydration with pending chunks and repeated module-load failures.Priority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~25 minutes
Change: Bug fix
Sequence Diagram(s)#
Merge Risk: ⚪ Minimal · up to
db254Hydration can complete before component chunks arrive while still waiting for lazy route options. No actionable merge-blocking issue remains; merge after normal checks pass.
Security Architecture Review#
Security architecture risk: 🔵 Low · up to
db254No new privilege or data-access expansion was demonstrated. Navigation ownership checks remain in place, but failed-download and reload recovery are not fully verified end to end.
Retained concerns No architecture-level concerns identified.
Security review details
Security Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 3.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 14 files. (2 skipped: 2 unsupported.)
✨ 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