Skip to content

Conversation

Sheraff
Copy link
Contributor

@Sheraff Sheraff commented Aug 16, 2025

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.

Copy link

coderabbitai bot commented Aug 16, 2025

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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

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.

Copy link

nx-cloud bot commented Aug 16, 2025

View your CI Pipeline Execution ↗ for commit 0ec2d48

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:39 UTC

Copy link

pkg-pr-new bot commented Aug 16, 2025

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 1720f28 and 0ec2d48.

📒 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.

@Sheraff Sheraff merged commit d00b9c1 into main Aug 16, 2025
6 checks passed
@Sheraff Sheraff deleted the refactor-router-core-fewer-get-match-calls branch August 16, 2025 19:06
Comment on lines 322 to 334
const then = () => {
let shouldExecuteBeforeLoad = true
let result = true
const match = inner.router.getMatch(matchId)!
if (match.status === 'error') {
shouldExecuteBeforeLoad = true
result = true
} else if (
match.preload &&
(match.status === 'redirected' || match.status === 'notFound')
) {
handleRedirectAndNotFound(inner, match, match.error)
}
return shouldExecuteBeforeLoad
return result
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the result is always true here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Damn you're right. The PR that made this change is this one though: #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!

Copy link
Contributor Author

@Sheraff Sheraff Aug 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a PR for the cleanup #4992, and a follow up (wip) for actually re-thinking what should happen there #4993

Sheraff added a commit that referenced this pull request Aug 19, 2025
Fix #4971 (comment)

With the code now simplified by previous PRs, we noticed that the
`shouldExecuteBeforeLoad` guard is always true, so we can clean it up.

In a follow up PR, we'll revise the conditions under which a
`beforeLoad` should be called or skipped.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Refactor**
* Streamlined pre-load checks and execution flow, reducing branching and
improving consistency across client and server rendering.
* Unified orchestration of the before-load phase to simplify control
flow and improve maintainability.

* **Bug Fixes**
* More reliable handling of redirects and “not found” states during
preloading, preventing unintended execution paths and improving
navigation stability.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
tannerlinsley pushed a commit that referenced this pull request Aug 26, 2025
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

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## 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.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
tannerlinsley pushed a commit that referenced this pull request Aug 26, 2025
Fix #4971 (comment)

With the code now simplified by previous PRs, we noticed that the
`shouldExecuteBeforeLoad` guard is always true, so we can clean it up.

In a follow up PR, we'll revise the conditions under which a
`beforeLoad` should be called or skipped.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Refactor**
* Streamlined pre-load checks and execution flow, reducing branching and
improving consistency across client and server rendering.
* Unified orchestration of the before-load phase to simplify control
flow and improve maintainability.

* **Bug Fixes**
* More reliable handling of redirects and “not found” states during
preloading, preventing unintended execution paths and improving
navigation stability.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants