Skip to content
Source
Sign inSign up
TanStack/router

fix(router-core, react-router): keep a departed match readable until its tree unmounts #8576

OpenTarekkharsa(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/8576/headopened

🎯 Changes

Fixes #8198. Related: #8306.

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:

  • MatchImpl gives undefined to MatchView.
  • Outlet reads _notFound from the cleared parent store. It also uses ids[ids.indexOf(routeId) + 1], and indexOf returns -1, so it renders the root route inside itself.
  • useMatch finds no match and throws.

Fix

  • router-core/stores.ts: setMatches saves the previous ids in stores.previousIds. It also keeps the last match of each route that left in stores.departed (the same objects, no copies). Both are written in the batch that clears the departed stores and cleared at the next change of ids, so they hold at most one entry per route.
  • react-router/Match.tsx: MatchImpl and the Outlet parent selector use stores.departed as a fallback. If no match exists, MatchImpl renders null. Outlet finds the child id in previousIds when its route has left, so it never uses index -1.
  • react-router/useMatch.tsx: uses stores.departed only 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. useMatch now always reads matchContext, so the PR removes the unused dummyMatchContext.

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:

  1. 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 /a has 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 /b renders one time and that no error callback fires. On main, this test fails with the routeId TypeError.
  2. It checks that useMatch({ from: '/a' }) inside /b still 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. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      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: 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.tsx
      • packages/react-router/src/matchContext.tsx
      💤 Files with no reviewable changes (1)
      • packages/react-router/src/matchContext.tsx

      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

      Layer / File(s)Summary
      Capture matches for removed routes
      packages/router-core/src/stores.ts
      RouterStores now exposes previous route IDs and departed matches. When route IDs change, setMatches saves matches for removed routes before clearing their stores.
      Render exiting route trees from retained matches
      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.md
      Match, Outlet, and useMatch use 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)

      sequenceDiagram
        participant RouterStores
        participant Match
        participant Outlet
        participant useMatch
        RouterStores->>Match: Retain the removed route's last match
        Match->>RouterStores: Read active or departed match
        Outlet->>RouterStores: Read parent state and route IDs
        useMatch->>RouterStores: Select departed match when the nearest route is departed

      Possibly related PRs

      • TanStack/router#8485: Both PRs retain previous route IDs and departed matches, then use them in React Router bindings while preserving inactive-route errors.

      Suggested reviewers: sheraff

      Merge Risk: 🔵 Low · up to 768bc

      A 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 2ee81

      The 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

      • inferred — The demonstrated exposure is prior match state within the same router instance and its client-rendered trees. The inspected paths do not establish an independently attackable cross-tenant, service, or credential boundary.

      Trust Boundaries and Controls

      • observed — useMatch first prefers active state and permits departed fallback only when the nearest route in React context is itself departed. An active B tree requesting departed A therefore retains the normal inactive-match error. This is a rendering-scope control, not an authorization mechanism.

      Resilience and Maintainability Implications

      • inferred — Pending offers can publish presentation state before commit. Inspected cancellation paths clear pending-session resources but do not themselves demonstrate restoration of committed matches. This publication behavior predates the PR; its interaction with newly retained data remains a recovery-coverage gap, not an established security regression.
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 4 files.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly summarizes the primary change: retaining departed matches so they remain readable until the old route tree unmounts.
      Description check✅ PassedThe description is complete and relevant. It explains the problem, root cause, fix, tests, validation results, release impact, and checklist status. It also documents the generated changeset.
      Linked Issues check✅ PassedThe PR meets the coding requirements in #8198. setMatches stores previousIds and departed match objects before clearing departed stores. MatchImpl, Outlet, and useMatch read this state for t…
      Out of Scope Changes check✅ PassedThe changes stay within #8198. The router-core state, React fallback readers, focused regression tests, and release changeset directly support the interrupted hydration fix. Removing `dummyMatchContex…
      • Fix all pre-merge checks with AI
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR
      • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      Autopilot is currently an internal CodeRabbit preview.


      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
      Comment `@coderabbitai help` to get the list of available commands.
    2. @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.

    3. 🦋 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
      NameType
      @tanstack/router-corePatch
      @tanstack/react-routerPatch
      @tanstack/react-start-clientPatch
      @tanstack/react-start-rscPatch
      @tanstack/react-start-serverPatch
      @tanstack/router-generatorPatch
      @tanstack/router-pluginPatch
      @tanstack/solid-routerPatch
      @tanstack/solid-start-clientPatch
      @tanstack/solid-start-serverPatch
      @tanstack/start-client-corePatch
      @tanstack/start-plugin-corePatch
      @tanstack/start-server-corePatch
      @tanstack/start-storage-contextPatch
      @tanstack/vue-routerPatch
      @tanstack/vue-start-clientPatch
      @tanstack/vue-start-serverPatch
      @tanstack/react-startPatch
      @tanstack/router-cliPatch
      @tanstack/router-vite-pluginPatch
      @tanstack/solid-startPatch
      @tanstack/start-static-server-functionsPatch
      @tanstack/vue-startPatch

      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

    4. Rebased onto main (663282b0e). The only conflict was in Match.tsx, where #8594 turned MatchView into matchView(). MatchImpl still falls back to stores.departed and returns null when it has no match, then calls matchView(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
      main 663282b0e3/3 fail (Invariant failed in useMatch, then React #520 and #422)3/3 ok1
      this branch 768bca8b13/3 ok3/3 ok0

      The route boundary was still dehydrated at every click in both builds.

      Exit 0 locally on the rebased branch: @tanstack/router-core and @tanstack/react-router test:unit (3639 and 1241 tests), test:types and test: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.

    5. Friendly ping: Tanner's TanStack/tanstack.com#1358 traced tanstack.com's production _notFound crash 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.

    6. Friendly ping: Tanner's TanStack/tanstack.com#1358 traced tanstack.com's production _notFound crash 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.

Sign in to join this conversation.