Skip to content

Commit 6b845f6

Browse files
authored
fix: router performance (#381)
PR #372 ("enhanced router") introduced a regression where every `<Route>` in a layout caused the SSR worker to import the target page module and the browser to preload its chunk, even for non-matching siblings. On large layouts this dominated request latency and forced every client chunk into the initial download. This PR removes that cost without giving up the correctness or DX of the new router. The core idea is to keep live client references out of the Flight payload for routes that don't match. The file router now emits `<Route componentId="…" componentLoader={() => Page} />` instead of `<Route element={<Page/>} />`. The live reference only exists inside the closure body, so React's RSC encoder walks past it for non-matching siblings and never registers the chunk. Only the matching route calls `componentLoader()` and instantiates the page, which produces exactly one client-reference registration per request. For non-matching routes we resolve the source-relative `$id` to the built chunk URL via `clientReferenceMap` (with a try/catch fallback to the source module so dev still works without the `.react-server/` build output) and pass the chunk id to the client. On the client, `ClientRouteRegistration` builds a small `LazyChunkComponent` wrapper around the deferred chunk. It deliberately does not use `React.lazy`, because `lazy` always schedules a microtask before re-rendering and causes a one-frame fallback flash even when the module is already in the `__webpack_require__` cache. Instead the wrapper reads `p.value` synchronously on cache hits and falls through to React 19's `use(p)` hook only when the import is genuinely in flight. It also patches `.value`/`.status` onto the import promise itself, since the prod polyfill in `render-rsc.jsx` does this on the server but Vite's dev `__webpack_require__` does not. There is a load-bearing invariant: in lazy mode the wrapper is only instantiated when the route is active, because Activity hidden subtrees still render and would otherwise eagerly fire the dynamic import for every sibling. The lazy render path also intentionally has no local Suspense boundary, so an active route's suspension propagates to the navigation transition and React keeps the previous page visible until the new chunk resolves, instead of flashing a blank fallback. The second half of this PR is an unrelated scroll-restoration bug surfaced by the new lazy navigation timing. `ScrollRestoration` initialised its `lastY` snapshot from `window.scrollY` at effect setup time, but on `popstate` the browser carries the previous page's scroll position over because we set `history.scrollRestoration = "manual"`. If a fast follow-up navigation ran the cleanup before any real scroll event refreshed the snapshot, the cleanup would write the previous route's scroll value under the current route's key, silently corrupting saved positions. The fix introduces a module-level `scrollObserved` flag that the window scroll listener and every container scroll listener flip on first event, and the cleanup only persists if a real scroll has been observed for that route. If nothing scrolled, the existing storage entry is correct and we leave it alone. This affects real users on any quick back/forward navigation, not just tests. The scroll restoration test file was also rewritten to boot the dev server once via `beforeAll` (the previous per-test `await server(...)` was rebuilding the dev server before every test and dominating the suite duration — 63s down to 17s), with a `beforeEach` that navigates to the fixture origin first and *then* clears `sessionStorage`, since storage is per-origin and clearing on `about:blank` is a no-op for the test origin. Finally, the benchmark example was restructured into `(rsc)`, `(ssr)`, and `(hybrid)` route groups, and `bench.mjs` now exposes a `--filter` flag for local iteration plus a new set of hybrid benchmarks that exercise the layout-with-many-client-siblings shape this PR is designed to make fast. Original benchmark URLs are unchanged (route groups are transparent), so the CI baseline comparison still works without modification.
1 parent 249497a commit 6b845f6

41 files changed

Lines changed: 1345 additions & 289 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

examples/benchmark/bench.mjs

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ const saveLabel = args.includes("--save")
2828
const compareFile = args.includes("--compare")
2929
? args[args.indexOf("--compare") + 1]
3030
: null;
31+
const filterArg = args.includes("--filter")
32+
? args[args.indexOf("--filter") + 1]
33+
: null;
34+
const filters = filterArg
35+
? filterArg
36+
.split(",")
37+
.map((s) => s.trim())
38+
.filter(Boolean)
39+
: null;
3140

3241
function parseCluster() {
3342
const idx = args.findIndex((a) => a.startsWith("--cluster"));
@@ -161,7 +170,48 @@ const BENCHMARKS = [
161170
desc: "Static file (JS bundle)",
162171
},
163172
{ name: "404-miss", path: "/nonexistent", desc: "404 miss → SSR" },
164-
];
173+
{
174+
name: "hybrid-min",
175+
path: "/hybrid",
176+
desc: "Hybrid server+6 client siblings (min)",
177+
},
178+
{ name: "hybrid-small", path: "/hybrid/small", desc: "Hybrid small" },
179+
{ name: "hybrid-medium", path: "/hybrid/medium", desc: "Hybrid medium" },
180+
{ name: "hybrid-large", path: "/hybrid/large", desc: "Hybrid large" },
181+
{ name: "hybrid-deep", path: "/hybrid/deep", desc: "Hybrid deep" },
182+
{ name: "hybrid-wide", path: "/hybrid/wide", desc: "Hybrid wide" },
183+
{ name: "hybrid-cached", path: "/hybrid/cached", desc: "Hybrid cached" },
184+
{
185+
name: "hybrid-client-min",
186+
path: "/hybrid/client",
187+
desc: "Hybrid client minimal",
188+
},
189+
{
190+
name: "hybrid-client-small",
191+
path: "/hybrid/client/small",
192+
desc: "Hybrid client small",
193+
},
194+
{
195+
name: "hybrid-client-medium",
196+
path: "/hybrid/client/medium",
197+
desc: "Hybrid client medium",
198+
},
199+
{
200+
name: "hybrid-client-large",
201+
path: "/hybrid/client/large",
202+
desc: "Hybrid client large",
203+
},
204+
{
205+
name: "hybrid-client-deep",
206+
path: "/hybrid/client/deep",
207+
desc: "Hybrid client deep",
208+
},
209+
{
210+
name: "hybrid-client-wide",
211+
path: "/hybrid/client/wide",
212+
desc: "Hybrid client wide",
213+
},
214+
].filter((b) => !filters || filters.some((f) => b.name.includes(f)));
165215

166216
// ── Find an actual JS bundle path ───────────────────────────────────────────
167217

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export default function Layout({ children }) {
2+
return children;
3+
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)