fix(router-core, react-router): keep a departed match readable until its tree unmounts #8576
main fromrefs/pull/8576/head·opened 🎯 Changes#
Supersedes #8485 (moved from my work account).
Reproducer: https://github.com/Tarekkharsa/tanstack-router-departed-match-repro. On the current release, pnpm i && pnpm test exits 1.
Problem#
In an SSR app, the user can click a <Link> in the header while the route content's Suspense boundary is still dehydrated. This happens often on React 19, because React hydrates that boundary later than the header. React discards the hydration and logs #422/#520, and in trees with nested outlets the recovery render throws again (MatchView routeId TypeError / useMatch invariant):
TypeError: Cannot read properties of undefined (reading 'routeId') // MatchView
Invariant failed: Could not find a nearest match! // useMatch
Root cause#
setMatches clears the store of each route that the user leaves, in the same batch that commits the navigation. Before React unmounts the old tree, it hydrates the dehydrated boundary one time with the old children. In that render:
MatchImplgivesundefinedtoMatchView.Outletreads_notFoundfrom the cleared parent store. It also usesids[ids.indexOf(routeId) + 1], andindexOfreturns-1, so it renders the root route inside itself.useMatchfinds no match and throws.
Fix#
router-core/stores.ts:setMatchessaves the previous ids instores.previousIds. It also keeps the last match of each route that left instores.departed(the same objects, no copies). Both are written in the batch that clears the departed stores and cleared at the next change ofids, so they hold at most one entry per route.react-router/Match.tsx:MatchImpland theOutletparent selector usestores.departedas a fallback. If no match exists,MatchImplrendersnull.Outletfinds the child id inpreviousIdswhen its route has left, so it never uses index-1.react-router/useMatch.tsx: usesstores.departedonly when the nearest route in context has itself left, that is, only inside the old tree. From a live tree,useMatch({ from })for an inactive route still throws, as before.useMatchnow always readsmatchContext, so the PR removes the unuseddummyMatchContext.
Only the old tree reads the departed state, and only for the one render before it unmounts. The core change only adds state, so Solid and Vue do not change.
Why not just return null in MatchImpl? That stops the throw, but then the client renders nothing where the server HTML has content. React logs a recoverable hydration error and client-renders the boundary. The departed map keeps the one hydration render equal to the server HTML, so onRecoverableError stays empty.
If the user navigates twice before the old tree hydrates, React tries one hydration per lane and then client-renders the new children; the null path in MatchImpl is only a guard for that case.
Tests#
packages/react-router/tests/departed-match-dehydrated-boundary.test.tsx uses only public APIs:
- It server-renders
/a/child, hydrates it with a child that stays suspended, and clicks a root link to/b. Before the click it asserts that/ahas not committed on the client, so the boundary is provably still dehydrated and the result does not depend on React scheduling. It then checks that/brenders one time and that no error callback fires. Onmain, this test fails with therouteIdTypeError. - It checks that
useMatch({ from: '/a' })inside/bstill throws.
If you revert any one of the reader changes, a test fails.
Local runs on main at d35aab425b (after #8579), all exit 0: test:unit, test:eslint, test:types, build, test:build for router-core and react-router, and test:unit for solid-router and vue-router. With only the src changes reverted, the new test fails with the routeId TypeError. Bundle size of react-router.minimal: +103 bytes gzip (85965 to 86068).
Follow-up: in the departed render, useParentMatches / useChildMatches return a wrong slice (no throw). Not changed here.
✅ 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.
🚀 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
- Fixed navigation during hydration when a previously displayed route is still mounted. The new page can render without errors while the old route finishes hydrating.
- Preserved access to the departing route’s match within its still-rendering route tree during hydration.
useMatch({ from })continues to report an error when the requested route is no longer active, rather than returning a match from a different page.
- 1
@Sheraff could you take a look when you have time? This fixes #8198 (reproducer linked in the description). The workflows need approval to run, since this is my first PR from this account.
🦋 Changeset detected#
Latest commit: 768bca8b1f206b3db6b5ba53ca01941fc97f28e9
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 23 packages
Name Type @tanstack/router-core Patch @tanstack/react-router Patch @tanstack/react-start-client Patch @tanstack/react-start-rsc Patch @tanstack/react-start-server Patch @tanstack/router-generator Patch @tanstack/router-plugin Patch @tanstack/solid-router Patch @tanstack/solid-start-client Patch @tanstack/solid-start-server Patch @tanstack/start-client-core Patch @tanstack/start-plugin-core Patch @tanstack/start-server-core Patch @tanstack/start-storage-context Patch @tanstack/vue-router Patch @tanstack/vue-start-client Patch @tanstack/vue-start-server Patch @tanstack/react-start Patch @tanstack/router-cli Patch @tanstack/router-vite-plugin Patch @tanstack/solid-start Patch @tanstack/start-static-server-functions Patch @tanstack/vue-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
Rebased onto
main(663282b0e). The only conflict was inMatch.tsx, where #8594 turnedMatchViewintomatchView().MatchImplstill falls back tostores.departedand returnsnullwhen it has no match, then callsmatchView(router, match).The bug still reproduces on
main, after #8594 and #8602. I ran the reproducer against packages packed from each commit, at 6x CPU throttling with 3 runs per journey:Build /items/1 -> //catalog -> /(control)Exit main663282b0e3/3 fail ( Invariant failedinuseMatch, then React #520 and #422)3/3 ok 1 this branch 768bca8b1 3/3 ok 3/3 ok 0 The route boundary was still dehydrated at every click in both builds.
Exit 0 locally on the rebased branch:
@tanstack/router-coreand@tanstack/react-routertest:unit(3639 and 1241 tests),test:typesandtest:eslint.@Sheraff @schiller-manuel could one of you approve the workflow runs? This is my first PR from this account, so CI has not run yet. #8577 builds on this one.
Friendly ping: Tanner's TanStack/tanstack.com#1358 traced tanstack.com's production
_notFoundcrash to this bug. The workflows here are still waiting for approval (first PR from this account). Could a maintainer approve them so CI can run? Happy to address any feedback.Friendly ping: Tanner's TanStack/tanstack.com#1358 traced tanstack.com's production
_notFoundcrash to this bug. The workflows here are still waiting for approval (first PR from this account). Could a maintainer approve them so CI can run? Happy to address any feedback.we're looking into hydration more generally. I haven't forgotten your PR, but a more encompassing PR might supersede it and fix hydration issues holistically, which usually yields a better result than many small fixes.
Tarekkharsa(GitHub profile, opens in a new tab) linked this to fix #8198
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
e5029c2e-6265-4a0d-a431-2eea93ef27cf📥 Commits
Reviewing files that changed from the base of the PR and between 2ee81aad991dc60fe0e579e9353da9e2a3e3aab5 and 768bca8b1f206b3db6b5ba53ca01941fc97f28e9.
📒 Files selected for processing (2)
packages/react-router/src/Match.tsxpackages/react-router/src/matchContext.tsx💤 Files with no reviewable changes (1)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
📝 Walkthrough
Walkthrough#
Router stores now retain previous route IDs and the last matches for routes removed from the active match set. React bindings use retained matches when rendering an exiting route tree.
useMatch({ from })still rejects inactive routes outside that tree.Changes#
Departed route match handling
packages/router-core/src/stores.tsRouterStoresnow exposes previous route IDs and departed matches. When route IDs change,setMatchessaves matches for removed routes before clearing their stores.packages/react-router/src/Match.tsx,packages/react-router/src/matchContext.tsx,packages/react-router/src/useMatch.tsx,packages/react-router/tests/departed-match-dehydrated-boundary.test.tsx,.changeset/departed-match-dehydrated-boundary.mdMatch,Outlet, anduseMatchuse departed-match data when active matches are absent. Tests cover hydration during navigation and the inactive-route invariant outside the departed route tree. The changeset declares patch releases for both packages.Priority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix · Severity of issue fixed: Medium
Sequence Diagram(s)#
Possibly related PRs
Suggested reviewers:
sheraffMerge Risk: 🔵 Low · up to
768bcA rapid second navigation before a dehydrated route finishes exiting may leave its stale render without the correct match and cause a render error. The risk is narrow; the change is mergeable with bounded follow-up on retaining matches for outstanding renders.
Security Architecture Review#
Security architecture risk: 🔵 Low · up to
2ee81The change retains prior route data to support a tree that has not finished unmounting. Active-tree lookups remain restricted, and no security bypass was established. Cancellation and overlapping navigation behavior remain partly unverified.
Retained concerns No architecture-level concerns identified.
Security review details
Security Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
#8198.setMatchesstorespreviousIdsand departed match objects before clearing departed stores.MatchImpl,Outlet, anduseMatchread this state for t…#8198. The router-core state, React fallback readers, focused regression tests, and release changeset directly support the interrupted hydration fix. Removing `dummyMatchContex…✨ 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