refactor(router-core): Verify changes are necessary before updating store #4964
main fromrefs/pull/4964/head·merged by Sheraff(GitHub profile, opens in a new tab) Following https://github.com/TanStack/router/pull/4916, https://github.com/TanStack/router/pull/4925, https://github.com/TanStack/router/pull/4926, and https://github.com/TanStack/router/pull/4928, this PR keeps reducing the number of store updates (__store.setState through updateMatch).
We check the values we want to set in the store are actually different from what is already in the store before calling updateMatch
In the store-updates-during-navigation test tracking the number of executions of a useRouterState > select method during a navigation, our main test case goes from 14 calls without this PR, to 10 calls with this PR. Most test cases show significant improvements as well.
Should be a partial improvement of https://github.com/TanStack/router/issues/4359
Summary by CodeRabbit#
Bug Fixes
- Prevented loss of previously loaded data during navigation when a loader yields no value.
- Stabilized preloading to avoid redundant updates and unnecessary state churn.
- Improved loading-state cleanup after navigation, reducing flicker and inconsistent “fetching” indicators.
Performance
- Reduced unnecessary state updates and re-renders during and after preloads/loads for smoother navigation.
Tests
- Updated async navigation tests to reflect refined timing and data-return behavior and added a helper to simulate delayed async results.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-router
View your CI Pipeline Execution ↗ for commit 4a45c06bf59962200dac2cf61c236b73ea6f36e4
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded 6m 30s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 1m 34s View ↗
☁️ Nx Cloud last updated this comment at
2025-08-16 11:39:51UTCgithub-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
More 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@4964@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@4964@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@4964@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@4964@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@4964@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@4964@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@4964@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@4964@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@4964@tanstack/react-start-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-plugin@4964@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@4964@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@4964@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@4964@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@4964@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@4964@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@4964@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@4964@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@4964@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@4964@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@4964@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@4964@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@4964@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@4964@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@4964@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@4964@tanstack/solid-start-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-plugin@4964@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@4964@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@4964@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@4964@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@4964@tanstack/start-server-functions-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-client@4964@tanstack/start-server-functions-fetcher
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-fetcher@4964@tanstack/start-server-functions-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-server@4964@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@4964@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@4964@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@4964@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@4964commit:
4a45c06Actionable comments posted: 0
🧹 Nitpick comments (3)
packages/router-core/src/router.ts (1)
2842-2854: Preload computation + conditional update looks good; minor nit on early loaderPromise creationComputing
nextPreloadand only updating when it differs reduces store churn. One nit:match._nonReactive.loaderPromiseis created unconditionally even when no loader will run and we’ll resolve it immediately later. Consider lazily creating it only in the branches that actually run a loader to trim unnecessary promise churn. Not a blocker.packages/react-router/tests/store-updates-during-navigation.test.tsx (2)
107-110: Type the helper to return the awaited valueresolveAftercurrently returnsPromise<void>but resolves withvalue. This compiles due to loose typing but is misleading and weakens type-safety.Apply this diff:
-function resolveAfter(ms: number, value: any) { - return new Promise<void>((resolve) => setTimeout(() => resolve(value), ms)) -} +function resolveAfter<T>(ms: number, value: T): Promise<T> { + return new Promise<T>((resolve) => setTimeout(() => resolve(value), ms)) +}
170-172: Deflake the “nothing” test to avoid timing varianceThe >=>= range and “flaky” note suggest timer/tick race. Consider using fake timers to control
pendingMs/pendingMinMstiming and eliminate nondeterminism:vi.useFakeTimers()before the test- Advance deterministically:
vi.advanceTimersByTime(...) await Promise.resolve()between advances if needed to flush microtasks
Not required for this PR, but it will make this assertion stable.
📜 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 1ccf7c827a6ba890fa9d835fd6ab3560cf99a1fe and 05b5122fa0c0977ca80da2e0c00bb643188ef709.
📒 Files selected for processing (2)
packages/react-router/tests/store-updates-during-navigation.test.tsx(6 hunks)packages/router-core/src/router.ts(3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/router-core/src/router.ts (4)
packages/router-core/src/utils.ts (1)
createControlledPromise(398-422)
packages/router-core/src/index.ts (1)
createControlledPromise(278-278)
packages/react-router/src/index.tsx (1)
createControlledPromise(35-35)
packages/solid-router/src/index.tsx (1)
createControlledPromise(35-35)
⏰ 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 (3)
packages/router-core/src/router.ts (2)
2901-2914: LGTM: precise end-of-load cleanup reduces unnecessary store writes- Clearing
pendingTimeoutand resetting its field unconditionally - Only resetting
loaderPromisewhen not running async - Resetting
dehydrated - Change-aware
isFetching/invalidupdate
All of this helps minimize redundant updates and avoids flicker.
2690-2706: Preserve the existing undefined‐guard to avoid unintended data clearsThe current
if (loaderData !== undefined)check is intentional: many loaders (especially those with a curly‐block body and no explicitreturn) implicitly returnundefined, and we rely on that to prevent child or auxiliary loaders from wiping out previously fetched data. Applying the suggested change would clear validloaderDatawhenever a loader doesn’t explicitly return a value—breaking existing tests and expected behavior.→ Retain the
loaderData !== undefinedguard as is.Likely an incorrect or invalid review comment.
packages/react-router/tests/store-updates-during-navigation.test.tsx (1)
125-125: Updated expectations align with fewer store updatesThe reduced update counts match the router-core’s conditional store writes and async handling tweaks. Looks good.
Also applies to: 143-144, 159-159, 170-172, 211-211
schiller-manuel(GitHub profile, opens in a new tab) approved these changes
Sheraff(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Walkthrough#
Refactors router load lifecycle to avoid writing undefined loaderData, compute and conditionally set preload, initialize per-match loaderPromise, and limit cleanup updates. Tests add a resolveAfter helper and lower expected store-update counts to match the new async behavior.
Changes#
packages/router-core/src/router.tsmatch.preloadwhen changed; initialize a fresh per-matchloaderPromisefor preloads; rework end-of-load cleanup (clear pending timeout, async gating forloaderPromisereset, resetdehydratedflag); minimizeisFetching/invalidupdates by comparing before writing.packages/react-router/tests/store-updates-during-navigation.test.tsxresolveAfter(ms, value)helper and replace inline Promises inbeforeLoad/loaderwith it; adjust multiple test expectations to lower update counts reflecting returned values and reduced store updates.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs#
Suggested reviewers#
Poem#
📜 Recent review details
Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro
💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between db78d61c8dba1fbc331b89de1ffd1919f9055563 and 4a45c06bf59962200dac2cf61c236b73ea6f36e4.
📒 Files selected for processing (1)
packages/router-core/src/router.ts(3 hunks)🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
✨ 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#