Skip to content
Source
Sign inSign up
TanStack/router

refactor(router-core): fewer getMatch calls #4971

MergedSheraff(GitHub profile, opens in a new tab)merged 3 commits intomain fromrefs/pull/4971/headmerged by Sheraff(GitHub profile, opens in a new tab)

some miscellaneous minor optimizations in the loadMatches pipeline.

  • try and reduce the number of times we call getMatch
  • onReady doesn't need to return a promise (because it's never used as such) actually some things fail without the artificially added microtask here
  • don't create beforeLoadPromise if there is no beforeLoad option anyway

Summary by CodeRabbit

  • Bug Fixes

    • Improved NotFound and error handling to prevent unnecessary blocking and ensure readiness triggers correctly.
    • More reliable SSR and preload behavior across route transitions.
  • Refactor

    • Streamlined route loading with per-route stale-while-revalidate, reducing redundant work and improving navigation responsiveness.
    • Reduced internal lookups and clarified readiness semantics for more predictable loading states.
  • Public API

    • onReady callback is now synchronous (no Promise), aligning with updated readiness flow.
    1. Walkthrough

      Refactors load-matches.ts to streamline match access, per-match state, and loader orchestration; adjusts NotFound/error handling; updates onReady to a non-async callback; removes unused imports; and revises SSR gating and head data updates while retaining the public loadMatches export.

      Changes

      Cohort / File(s)Summary
      Router core: loader orchestration and readiness semantics
      packages/router-core/src/load-matches.ts
      Simplified NotFound resolution; replaced router lookups with per-match state; refactored setupPendingTimeout and shouldExecuteBeforeLoad; revised executeBeforeLoad; overhauled load path with SWR, in-flight checks, and per-match minPending; gated SSR via match.ssr; adjusted readiness triggers; changed onReady type to () => void; removed ControlledPromise import.

      Sequence Diagram(s)

      sequenceDiagram
        participant Caller
        participant loadMatches
        participant Match
        participant BeforeLoad
        participant Loader
        participant UpdateMatch
        participant onReady
      
        Caller->>loadMatches: invoke({ matches, preload?, onReady?, sync? })
        loop for each Match
          loadMatches->>Match: evaluate shouldExecuteBeforeLoad()
          alt should execute
            loadMatches->>BeforeLoad: run beforeLoad
            loadMatches->>Match: setupPendingTimeout(match)
          end
          alt loaderPromise in-flight
            loadMatches-->>Match: early return (reuse promise)
          else SSR gated or no reload
            loadMatches->>UpdateMatch: update head/flags (no loader run)
          else should reload (SWR)
            loadMatches->>Loader: run loader (async)
            Loader-->>UpdateMatch: commit data/error
          end
        end
        alt onReady provided
          loadMatches->>onReady: call () => void
        end
        loadMatches-->>Caller: resolved matches
      sequenceDiagram
        participant loadMatches
        participant Matches
        participant NotFound
        participant UpdateMatch
      
        loadMatches->>Matches: process list
        alt NotFound route encountered
          loadMatches->>NotFound: resolve via matches.find(routeId===cursor.id)
          Note over loadMatches,NotFound: Trigger readiness without awaiting in some cases
          NotFound-->>UpdateMatch: mark error/not found
        end

      Estimated code review effort

      🎯 4 (Complex) | ⏱️ ~60 minutes

      • TanStack/router#4967 — Adjusts loadMatches coordination and ready signaling, overlapping with this PR’s readiness simplification.
      • TanStack/router#4961 — Direct edits to the same loadMatches helpers and flow (pending timeout, loader lifecycle, readiness).
      • TanStack/router#4964 — Related refactors to per-match loader state and pending timeouts consistent with this overhaul.

      Suggested reviewers

      • schiller-manuel

      Poem

      A rabbit hops through routes at night, Tidying loaders with gentle might. NotFound burrows neatly aligned, SSR gates calmly defined. onReady squeaks—no promise to chew— Fresh carrots, stale while I renew. Hop, commit, and off I flew! 🥕🐇

      ✨ Finishing Touches
      • 📝 Generate Docstrings
        🧪 Generate unit tests
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `refactor-router-core-fewer-get-match-calls`

      🪧 Tips

      Chat

      There are 3 ways to chat with CodeRabbit:

      • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
        • I pushed a fix in commit <commit_id>, please review it.
        • Open a follow-up GitHub issue for this discussion.
      • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
      • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
        • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
        • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

      Support

      Need help? Create a ticket on our support page for assistance with any issues or questions.

      CodeRabbit Commands (Invoked using PR/Issue comments)

      Type @coderabbitai help to get the list of available commands.

      Other keywords and placeholders

      • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
      • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
      • Add @coderabbitai anywhere in the PR title to generate the title automatically.

      CodeRabbit Configuration File (.coderabbit.yaml)

      • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
      • Please see the configuration documentation for more information.
      • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

      Status, Documentation and Community

      • Visit our Status Page to check the current availability of CodeRabbit.
      • Visit our Documentation for detailed information on how to use CodeRabbit.
      • Join our Discord Community to get help, request features, and share feedback.
      • Follow us on X/Twitter for updates and announcements.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core

    3. View your CI Pipeline Execution ↗ for commit 0ec2d48b72785a609dca6da6e6d345664c02f35d

      CommandStatusDurationResult
      nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded4m 45sView ↗
      nx run-many --target=build --exclude=examples/*...✅ Succeeded1m 32sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-08-16 18:40:39 UTC

    4. More templates

      @tanstack/arktype-adapter

      npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@4971

      @tanstack/directive-functions-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@4971

      @tanstack/eslint-plugin-router

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

      @tanstack/history

      npm i https://pkg.pr.new/TanStack/router/@tanstack/history@4971

      @tanstack/react-router

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

      @tanstack/react-router-devtools

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

      @tanstack/react-router-ssr-query

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

      @tanstack/react-start

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@4971

      @tanstack/react-start-client

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@4971

      @tanstack/react-start-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-plugin@4971

      @tanstack/react-start-server

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@4971

      @tanstack/router-cli

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

      @tanstack/router-core

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

      @tanstack/router-devtools

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

      @tanstack/router-devtools-core

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

      @tanstack/router-generator

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

      @tanstack/router-plugin

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

      @tanstack/router-ssr-query-core

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

      @tanstack/router-utils

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

      @tanstack/router-vite-plugin

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

      @tanstack/server-functions-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@4971

      @tanstack/solid-router

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

      @tanstack/solid-router-devtools

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

      @tanstack/solid-start

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@4971

      @tanstack/solid-start-client

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@4971

      @tanstack/solid-start-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-plugin@4971

      @tanstack/solid-start-server

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@4971

      @tanstack/start-client-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@4971

      @tanstack/start-plugin-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@4971

      @tanstack/start-server-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@4971

      @tanstack/start-server-functions-client

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-client@4971

      @tanstack/start-server-functions-fetcher

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-fetcher@4971

      @tanstack/start-server-functions-server

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-server@4971

      @tanstack/start-storage-context

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@4971

      @tanstack/valibot-adapter

      npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@4971

      @tanstack/virtual-file-routes

      npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@4971

      @tanstack/zod-adapter

      npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@4971

      commit: 0ec2d48

    5. Actionable comments posted: 0

      🧹 Nitpick comments (6)
      packages/router-core/src/load-matches.ts (6)

      75-83: Guard against missing match when handling NotFound (fallback to root match).

      If err.routeId targets a route that isn’t present in inner.matches (e.g., it's not part of the matched chain for this location), the invariant will throw. Consider falling back to the root route’s match to avoid crashing and still display the notFound component.

      -  // Find the match for this route
      -  const matchForRoute = inner.matches.find((m) => m.routeId === routeCursor.id)
      -
      -  invariant(matchForRoute, 'Could not find match for route: ' + routeCursor.id)
      +  // Find the match for this route (fallback to root route's match)
      +  let matchForRoute = inner.matches.find((m) => m.routeId === routeCursor.id)
      +  if (!matchForRoute) {
      +    matchForRoute = inner.matches.find((m) => m.routeId === rootRouteId)
      +  }
      +
      +  invariant(matchForRoute, 'Could not find match for route: ' + routeCursor.id)

      276-303: Passing the match into setupPendingTimeout is a solid cleanup.

      Nice reduction of lookups and clearer ownership of the pendingTimeout. Consider extracting the shouldPending condition into a helper for readability and testability, but not required.


      320-340: Simplify: then() always returns true; drop dead code and reduce re-reads.

      result is always true, so the conditional path doesn’t influence the return value. You can streamline to reduce noise and an extra getMatch call.

      -  const then = () => {
      -    let result = true
      -    const match = inner.router.getMatch(matchId)!
      -    if (match.status === 'error') {
      -      result = true
      -    } else if (
      -      match.preload &&
      -      (match.status === 'redirected' || match.status === 'notFound')
      -    ) {
      -      handleRedirectAndNotFound(inner, match, match.error)
      -    }
      -    return result
      -  }
      +  const then = () => {
      +    const match = inner.router.getMatch(matchId)!
      +    if (
      +      match.preload &&
      +      (match.status === 'redirected' || match.status === 'notFound')
      +    ) {
      +      handleRedirectAndNotFound(inner, match, match.error)
      +    }
      +    return true
      +  }

      401-409: Avoid bumping fetchCount for routes without beforeLoad.

      Even though updates are batched, calling pending() here increases fetchCount and transiently sets isFetching for a code path without beforeLoad. That can skew metrics/UI logic.

      If you adopt this, ensure abortController is initialized elsewhere before a loader runs (since pending() currently sets it).

      -  if (!route.options.beforeLoad) {
      -    batch(() => {
      -      pending()
      -      resolve()
      -    })
      -    return
      -  }
      +  if (!route.options.beforeLoad) {
      +    // No beforeLoad: avoid fetchCount bump and transient beforeLoad fetching
      +    inner.updateMatch(matchId, (prev) => ({
      +      ...prev,
      +      isFetching: false,
      +    }))
      +    return
      +  }

      760-829: SWR orchestration looks good; tiny clarity improvement for shouldReload.

      The SWR path is thoughtfully laid out. Minor readability nit: avoid nested ternary and redundant getLoaderContext invocation when shouldReload is a function.

      -      const shouldReload =
      -        typeof shouldReloadOption === 'function'
      -          ? shouldReloadOption(getLoaderContext(inner, matchId, index, route))
      -          : shouldReloadOption
      +      let shouldReload: boolean | undefined
      +      if (typeof shouldReloadOption === 'function') {
      +        const ctx = getLoaderContext(inner, matchId, index, route)
      +        shouldReload = shouldReloadOption(ctx)
      +      } else {
      +        shouldReload = shouldReloadOption
      +      }

      600-606: Typo in comment: double apostrophe in "we''ll".

      Minor doc fix.

      -    // a minimum duration, we''ll wait for it to resolve
      +    // a minimum duration, we'll wait for it to resolve
      📜 Review details

      Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro

      💡 Knowledge Base configuration:

      • MCP integration is disabled by default for public repositories
      • Jira integration is disabled by default for public repositories
      • Linear integration is disabled by default for public repositories

      You can enable these sources in your CodeRabbit configuration.

      📥 Commits

      Reviewing files that changed from the base of the PR and between 1720f28a5fc3d52035dcd89fbfd07ca2a6ab779f and 0ec2d48b72785a609dca6da6e6d345664c02f35d.

      📒 Files selected for processing (1)
      • packages/router-core/src/load-matches.ts (14 hunks)
      🧰 Additional context used
      🧬 Code Graph Analysis (1)
      packages/router-core/src/load-matches.ts (1)
      packages/router-core/src/index.ts (3)
      • AnyRouteMatch (90-90)
      • createControlledPromise (279-279)
      • isRedirect (373-373)
      ⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
      • GitHub Check: Test
      • GitHub Check: Preview
      🔇 Additional comments (6)
      packages/router-core/src/load-matches.ts (6)

      242-259: LGTM: SSR context now reuses per-match state.

      Using existingMatch to build the SSR context reduces re-fetches and keeps the flow coherent. Looks good.


      507-513: LGTM: Clear execution gate for beforeLoad.

      The execute closure is concise and the condition aligns with the upstream decision.


      581-582: AbortController wiring: verify initialization when beforeLoad is absent.

      getLoaderContext pulls abortController from the match. With the optimization above (if applied), ensure it’s still set for loader consumers in routes without beforeLoad. If not, consider initializing it in the loader path.


      607-614: LGTM: SSR-gated chunk preloading respects per-match ssr.

      Good call to gate loadRouteChunk with match.ssr on the server and allow on the client.


      746-756: LGTM: Early-return when a non-preload in-flight load has fresh data.

      Returning the current successful match without blocking fits the stale-while-revalidate strategy and avoids unnecessary waiting when sync is false.


      630-631: minPendingPromise lifecycle verified as correct.

      • Promises are created in both client (packages/react-router/src/Match.tsx & packages/solid-router/src/Match.tsx) and SSR hydration (packages/router-core/src/ssr/ssr-client.ts) whenever pendingMinMs is set.
      • Each promise is always resolved by its setTimeout handler and immediately cleared (minPendingPromise = undefined).
      • In load-matches.ts, any existing promise is awaited before proceeding or error handling, ensuring no accidental long waits or dangling promises.

      No changes required.

    6. packages/router-core/src/load-matches.ts lines 322 to 334
      @@ -325,17 +318,17 @@
      325318 return true
      326319
      327- setupPendingTimeout(inner, matchId, route)
      320+ setupPendingTimeout(inner, matchId, route, existingMatch)
      328321
      329322 const then = () => {
      330- let shouldExecuteBeforeLoad = true
      323+ let result = true
      331324 const match = inner.router.getMatch(matchId)!
      332325 if (match.status === 'error') {
      333- shouldExecuteBeforeLoad = true
      326+ result = true
      334327 } else if (
      335328 match.preload &&
      336329 (match.status === 'redirected' || match.status === 'notFound')
      337330 ) {
      338331 handleRedirectAndNotFound(inner, match, match.error)
      339332 }
      340- return shouldExecuteBeforeLoad
      333+ return result
      341334 }

      the result is always true here.

      Damn you're right. The PR that made this change is this one though: https://github.com/TanStack/router/pull/4961. I'll try and see if I can track down the original logic, but if you know what it's supposed to be already, I'm all ears!

      Actually it looks like it's been always true since this older PR https://github.com/TanStack/router/pull/4550/files (2 months ago). So I think we can at least say that it's not causing things to break. But maybe it is sub-optimal and we're executing too many beforeLoad calls. @schiller-manuel do you remember this a little?

      I have a PR for the cleanup https://github.com/TanStack/router/pull/4992, and a follow up (wip) for actually re-thinking what should happen there https://github.com/TanStack/router/pull/4993

    7. Sheraff(GitHub profile, opens in a new tab)replied on packages/router-core/src/load-matches.ts lines 322 to 334

      Damn you're right. The PR that made this change is this one though: https://github.com/TanStack/router/pull/4961. I'll try and see if I can track down the original logic, but if you know what it's supposed to be already, I'm all ears!

    8. Sheraff(GitHub profile, opens in a new tab)replied on packages/router-core/src/load-matches.ts lines 322 to 334

      Actually it looks like it's been always true since this older PR https://github.com/TanStack/router/pull/4550/files (2 months ago). So I think we can at least say that it's not causing things to break. But maybe it is sub-optimal and we're executing too many beforeLoad calls. @schiller-manuel do you remember this a little?

    9. Sheraff(GitHub profile, opens in a new tab)replied on packages/router-core/src/load-matches.ts lines 322 to 334

      I have a PR for the cleanup https://github.com/TanStack/router/pull/4992, and a follow up (wip) for actually re-thinking what should happen there https://github.com/TanStack/router/pull/4993

Sign in to join this conversation.