refactor(router-core): fewer getMatch calls #4971
main fromrefs/pull/4971/head·merged 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 actually some things fail without the artificially added microtask hereonReadydoesn't need to return a promise (because it's never used as such)- don't create
beforeLoadPromiseif there is nobeforeLoadoption 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
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
View your CI Pipeline Execution ↗ for commit 0ec2d48b72785a609dca6da6e6d345664c02f35d
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded 4m 45s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 1m 32s View ↗
☁️ Nx Cloud last updated this comment at
2025-08-16 18:40:39UTCMore templates
- tanstack-router-react-example-authenticated-routes
- tanstack-router-react-example-authenticated-routes-firebase
- tanstack-router-react-example-basic
- tanstack-router-react-example-basic-default-search-params
- tanstack-router-react-example-basic-devtools-panel
- tanstack-router-react-example-basic-file-based
- tanstack-router-react-example-basic-non-nested-devtools
- tanstack-router-react-example-react-query
- tanstack-router-react-example-basic-react-query-file-based
- tanstack-router-react-example-basic-ssr-file-based
- tanstack-router-react-example-basic-ssr-streaming-file-based
- tanstack-router-react-example-basic-virtual-file-based
- tanstack-router-react-example-basic-virtual-inside-file-based
- tanstack-router-react-example-deferred-data
- tanstack-router-react-example-kitchen-sink
- tanstack-router-react-example-kitchen-sink-file-based
- tanstack-router-react-example-kitchen-sink-react-query
- tanstack-router-react-example-kitchen-sink-react-query-file-based
- tanstack-router-react-example-large-file-based
- tanstack-router-react-example-location-masking
- tanstack-router-react-example-navigation-blocking
- tanstack-router-react-example-quickstart
- tanstack-router-react-example-quickstart-esbuild-file-based
- tanstack-router-react-example-quickstart-file-based
- tanstack-router-react-example-quickstart-rspack-file-based
- tanstack-router-react-example-quickstart-webpack-file-based
- router-monorepo-react-query
- router-mono-simple
- router-mono-simple-lazy
- tanstack-router-react-example-scroll-restoration
- tanstack-search-validator-adapters
- tanstack-start-example-bare
- tanstack-start-example-basic
- tanstack-start-example-basic-auth
- tanstack-start-example-basic-react-query
- tanstack-start-example-basic-rsc
- tanstack-start-example-basic-static
- tanstack-start-example-clerk-basic
- tanstack-start-example-convex-trellaux
- tanstack-start-example-counter
- tanstack-start-example-large
- tanstack-start-example-material-ui
- tanstack-start-example-supabase-basic
- tanstack-start-tailwind-v4
- tanstack-start-example-trellaux
- tanstack-start-example-workos
- tanstack-router-react-example-view-transitions
- tanstack-router-react-example-with-framer-motion
- tanstack-router-react-example-with-trpc
- tanstack-router-react-example-with-trpc-react-query
- tanstack-router-solid-example-basic
- tanstack-router-solid-example-basic-devtools-panel
- tanstack-router-solid-example-basic-file-based
- tanstack-router-solid-example-basic-non-nested-devtools
- tanstack-router-solid-example-basic-solid-query
- tanstack-router-solid-example-basic-solid-query-file-based
- tanstack-router-solid-example-basic-ssr-streaming-file-based
- tanstack-router-solid-example-kitchen-sink-file-based
- tanstack-router-solid-example-quickstart-file-based
- tanstack-solid-start-example-bare
- tanstack-solid-start-example-basic
- tanstack-solid-start-example-basic-static
@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@4971commit:
0ec2d48Actionable 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.routeIdtargets a route that isn’t present ininner.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 theshouldPendingcondition into a helper for readability and testability, but not required.
320-340: Simplify: then() always returns true; drop dead code and reduce re-reads.resultis alwaystrue, so the conditional path doesn’t influence the return value. You can streamline to reduce noise and an extragetMatchcall.- 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 increasesfetchCountand transiently setsisFetchingfor a code path withoutbeforeLoad. That can skew metrics/UI logic.If you adopt this, ensure
abortControlleris initialized elsewhere before a loader runs (sincepending()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
getLoaderContextinvocation whenshouldReloadis 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
existingMatchto build the SSR context reduces re-fetches and keeps the flow coherent. Looks good.
507-513: LGTM: Clear execution gate for beforeLoad.The
executeclosure is concise and the condition aligns with the upstream decision.
581-582: AbortController wiring: verify initialization when beforeLoad is absent.getLoaderContextpullsabortControllerfrom the match. With the optimization above (if applied), ensure it’s still set for loader consumers in routes withoutbeforeLoad. If not, consider initializing it in the loader path.
607-614: LGTM: SSR-gated chunk preloading respects per-match ssr.Good call to gate
loadRouteChunkwithmatch.ssron 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
syncis 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) wheneverpendingMinMsis set. - Each promise is always resolved by its
setTimeouthandler 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.
Sheraff(GitHub profile, opens in a new tab) closed this
- packages/router-core/src/load-matches.ts lines 322 to 334@@ -325,17 +318,17 @@325318 return true326319327- setupPendingTimeout(inner, matchId, route)320+ setupPendingTimeout(inner, matchId, route, existingMatch)328321329322 const then = () => {330- let shouldExecuteBeforeLoad = true323+ let result = true331324 const match = inner.router.getMatch(matchId)!332325 if (match.status === 'error') {333- shouldExecuteBeforeLoad = true326+ result = true334327 } else if (335328 match.preload &&336329 (match.status === 'redirected' || match.status === 'notFound')337330 ) {338331 handleRedirectAndNotFound(inner, match, match.error)339332 }340- return shouldExecuteBeforeLoad333+ return result341334 }
the result is always
truehere.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
truesince 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 manybeforeLoadcalls. @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
Sheraff(GitHub profile, opens in a new tab)replied on
packages/router-core/src/load-matches.tslines 322 to 334Damn 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!
Sheraff(GitHub profile, opens in a new tab)replied on
packages/router-core/src/load-matches.tslines 322 to 334Actually it looks like it's been always
truesince 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 manybeforeLoadcalls. @schiller-manuel do you remember this a little?Sheraff(GitHub profile, opens in a new tab)replied on
packages/router-core/src/load-matches.tslines 322 to 334I 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.
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#
packages/router-core/src/load-matches.tsSequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs#
Suggested reviewers#
Poem#
✨ Finishing Touches
🧪 Generate unit tests
🪧 Tips
Chat#
There are 3 ways to chat with CodeRabbit:
I pushed a fix in commit <commit_id>, please review it.Open a follow-up GitHub issue for this discussion.@coderabbitaiin a new review comment at the desired location with your query.@coderabbitaiin 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 helpto get the list of available commands.Other keywords and placeholders#
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed.@coderabbitai summaryto generate the high-level summary at a specific location in the PR description.@coderabbitaianywhere in the PR title to generate the title automatically.CodeRabbit Configuration File (
.coderabbit.yaml)#.coderabbit.yamlfile to the root of your repository.# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.jsonStatus, Documentation and Community#