refactor(router-core): skip beforeLoad and related store updates if options is not defined #4928
main fromrefs/pull/4928/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, and https://github.com/TanStack/router/pull/4926, this PR keeps reducing the number of store updates (__store.setState through updateMatch).
Early bail out of route before load step if route.options.beforeLoad is not defined
The store-updates-during-navigation test tracking the number of executions of a useRouterState > select method during a navigation goes from 17 calls without this PR, to 14 calls with this PR (or even 13 calls if beforeLoad is synchronous).
Should be a partial improvement of https://github.com/TanStack/router/issues/4359
Summary by CodeRabbit#
New Features
- Added a not-found helper and router options to configure a default Not Found component and a default preload strategy.
Refactor
- Streamlined the before-load lifecycle for more deterministic pending-state updates, earlier pending-timeout readiness, clearer parameter/search error surfacing, and adjusted context composition; loader error timing is more conservative.
Tests
- Expanded test coverage with new scenarios (sync before-load, not-found flow, hover-preload/navigation) and updated navigation update expectations.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-router
github-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@4928@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@4928@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@4928@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@4928@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@4928@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@4928@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@4928@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@4928@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@4928@tanstack/react-start-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-plugin@4928@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@4928@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@4928@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@4928@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@4928@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@4928@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@4928@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@4928@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@4928@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@4928@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@4928@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@4928@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@4928@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@4928@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@4928@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@4928@tanstack/solid-start-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-plugin@4928@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@4928@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@4928@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@4928@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@4928@tanstack/start-server-functions-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-client@4928@tanstack/start-server-functions-fetcher
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-fetcher@4928@tanstack/start-server-functions-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-server@4928@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@4928@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@4928@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@4928@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@4928commit:
8a7f954github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: solid-router
Walkthrough#
Reworks router-core beforeLoad and pending timing/flow with new helpers, AbortController-based pending lifecycle, earlier parse/validate error surfacing, batched state updates, and minor timing changes; adds tests and uses the new notFound export and router options. All production API signatures unchanged.
Changes#
Cohort / File(s) Summary of Changes Router core: beforeLoad / pending refactor packages/router-core/src/router.tsReworked beforeLoad orchestration: added helpers (shouldExecuteBeforeLoad, executeBeforeLoad, handleBeforeLoad, isBeforeLoadSsr), setupPendingTimeout earlier, create AbortController and pending()/resolve() flow, always invoke pending to render pending state, surface parse/validate errors earlier (PARSE_PARAMS / VALIDATE_SEARCH), support sync and async beforeLoad results, store __beforeLoadContext on match, batch state updates, remove defensive try/catch around triggerOnReady, and avoid awaiting potentialPendingMinPromise in loader error paths unless present. React Router tests packages/react-router/tests/store-updates-during-navigation.test.tsxExpanded tests and adjusted assertions: added import of fireEventandnotFound, useddefaultNotFoundComponentanddefaultPreloadrouter options in test setup, switched tofireEvent.clickfor navigation triggers, updated several expected update counts, and added new cases (sync beforeLoad, hover preload then navigate, not-found in beforeLoad, minimal "nothing" case). All changes confined to tests.Sequence Diagram(s)#
sequenceDiagram participant App participant Router participant Match participant BeforeLoad participant Loader participant Timer as PendingTimeout App->>Router: navigate(location, cause) Router->>Match: create AbortController, call pending() Router->>Timer: setupPendingTimeout() alt no beforeLoad Router-->>App: batched pending state rendered else beforeLoad present Router->>BeforeLoad: invoke (sync or async) with beforeLoadFnContext alt sync result Router-->>Match: merge context, set __beforeLoadContext (batched) else async result BeforeLoad-->>Router: resolve or throw Router-->>Match: merge context or handle BEFORE_LOAD error end end Timer-->>Router: pendingMs elapsed -> triggerOnReady() Router->>Loader: start loader (if applicable) alt error/redirect/notFound Router-->>App: handle error/redirect/notFound flow else success Router-->>App: render ready state endEstimated code review effort#
🎯 4 (Complex) | ⏱️ ~35 minutes
Possibly related PRs#
- TanStack/router#4961 — Overlapping edits to executeBeforeLoad, pending timing, and load pipeline; likely directly related.
Suggested reviewers#
- schiller-manuel
Poem#
Hop, hop — I check each route and trace, Timers set, beforeLoad finds its place. Sync results land, async waits take flight, Batched updates tidy up the night. Tests snugly pass — a carrot-coded sight 🥕
Tip
🔌 Remote MCP (Model Context Protocol) integration is now available!
Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.
✨ 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-skip-before-load`
🪧 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
@coderabbitaiin a new review comment at the desired location with your query. - PR comments: Tag
@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#
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere in the PR title to generate the title automatically.
CodeRabbit Configuration File (
.coderabbit.yaml)#- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile 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.
Actionable comments posted: 0
🧹 Nitpick comments (5)
packages/router-core/src/router.ts (4)
2321-2324: Make pending timeout resilient to async errors from onReadytriggerOnReadycan return a Promise. IfonReadyever throws/rejects, this can surface as an unhandled rejection in the timeout callback. Guard it defensively.Apply this diff:
- // Update the match and prematurely resolve the loadMatches promise so that - // the pending component can start rendering - this.triggerOnReady(innerLoadContext) + // Update the match and prematurely resolve the loadMatches promise so that + // the pending component can start rendering + const result = this.triggerOnReady(innerLoadContext) + if (isPromise(result)) void result.catch(() => {})
2416-2433: Return early after PARSE_PARAMS/VALIDATE_SEARCH errors to avoid unnecessary state churnWe already resolve promises and mark the match as errored in
handleSerialError. Continuing (setting pending timers, etc.) is unnecessary and slightly noisy. Early returns here keep the flow tighter and avoid extra updates.Apply this diff:
if (paramsError) { this.handleSerialError( innerLoadContext, index, paramsError, 'PARSE_PARAMS', ) + return } if (searchError) { this.handleSerialError( innerLoadContext, index, searchError, 'VALIDATE_SEARCH', ) + return }
2436-2443: Skip fetchCount bump and redundant state updates when no beforeLoad is definedThe bail-out path still invokes
pending()which incrementsfetchCountand assigns a newabortController, then immediately clears fetching in the same batch. Since there's no beforeLoad work, we can resolve the promise without touching the match state, further reducing updates and avoiding a misleading fetchCount bump.Apply this diff:
- // if there is no `beforeLoad` option, skip everything, batch update the store, return early + // if there is no `beforeLoad` option, skip everything, resolve, return early if (!route.options.beforeLoad) { - batch(() => { - pending() - resolve() - }) + resolve() return }
2462-2471: Guard against null (or non-object) beforeLoad returns when merging contextIf a route's
beforeLoadmistakenly returnsnull, the spread operator will throw. Treatundefined/nullas "no additional context".Apply this diff:
- innerLoadContext.updateMatch(matchId, (prev) => ({ - ...prev, - __beforeLoadContext: beforeLoadContext, - context: { - ...prev.context, - ...beforeLoadContext, - }, - })) + innerLoadContext.updateMatch(matchId, (prev) => { + const safeCtx = + beforeLoadContext && typeof beforeLoadContext === 'object' + ? beforeLoadContext + : {} + return { + ...prev, + __beforeLoadContext: safeCtx, + context: { + ...prev.context, + ...safeCtx, + }, + } + })packages/react-router/tests/store-updates-during-navigation.test.tsx (1)
134-148: Great addition: sync beforeLoad scenario coveredCovers a key path; expectation of 13 seems consistent with the new lifecycle.
Consider adding a couple of small follow-ups to lock in the bail-out and edge behaviors that this PR targets:
- A route with no beforeLoad: assert minimal updates (ensures the bail-out truly produces no extra store updates).
- A beforeLoad that returns undefined: behaves like “no context change”.
- A beforeLoad that returns null: if you keep the suggested guard, verify it doesn’t throw and produces no context merge.
I can draft these tests if helpful.
📜 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 9d4b7c2e698436b6b9bb057a5343061b325012d5 and 891b55cdc40dafaaedb09d77ca783e32c512bc8c.
📒 Files selected for processing (2)
packages/react-router/tests/store-updates-during-navigation.test.tsx(2 hunks)packages/router-core/src/router.ts(3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/router-core/src/router.ts (3)
packages/router-core/src/utils.ts (2)
createControlledPromise(398-422)isPromise(477-485)
packages/router-core/src/redirect.ts (1)
isRedirect(95-97)
packages/router-core/src/route.ts (1)
BeforeLoadContextOptions(966-977)
⏰ 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 (1)
2724-2726: Loader error path honors minPending only when present — LGTMAwaiting
potentialPendingMinPromise(matchId)conditionally avoids unnecessary waits and matches the intent. Looks good.packages/react-router/tests/store-updates-during-navigation.test.tsx (2)
113-114: Updated expectation reflects fewer store updates — LGTMThe drop to 14 aligns with the optimized beforeLoad/pending flow.
131-133: Preload redirection update count decreased — LGTMThe new expectation at 6 matches the refined error/pending timing.
Actionable comments posted: 1
🧹 Nitpick comments (3)
packages/router-core/src/router.ts (3)
2321-2324: Guard triggerOnReady to avoid unhandled rejections in setTimeout callbackRemoving the try/catch means any thrown error or rejected promise from
onReadywill become an unhandled error in the timeout callback. Wrap the call and catch async rejections to avoid noisy console errors in production and hard-to-reproduce bugs.- const pendingTimeout = setTimeout(() => { - // Update the match and prematurely resolve the loadMatches promise so that - // the pending component can start rendering - this.triggerOnReady(innerLoadContext) - }, pendingMs) + const pendingTimeout = setTimeout(() => { + // Update the match and prematurely resolve the loadMatches promise so that + // the pending component can start rendering + try { + const ready = this.triggerOnReady(innerLoadContext) + if (isPromise(ready)) { + ready.catch((err) => { + if (process.env.NODE_ENV !== 'production') { + console.error('[router] onReady failed during pending timeout', err) + } + }) + } + } catch (err) { + if (process.env.NODE_ENV !== 'production') { + console.error('[router] onReady threw during pending timeout', err) + } + } + }, pendingMs)
2403-2425: Reuse existing abortController instead of swapping in a new instanceCreating a new
AbortControllerhere replaces the one established when the match was created. That swaps cancellation tokens mid-flight and can be surprising for integrations holding a reference to the previous controller. Prefer reusing the existing controller when present.- const abortController = new AbortController() + const abortController = match.abortController ?? new AbortController() @@ - innerLoadContext.updateMatch(matchId, (prev) => ({ + innerLoadContext.updateMatch(matchId, (prev) => ({ ...prev, isFetching: 'beforeLoad', fetchCount: prev.fetchCount + 1, abortController, context, }))
2436-2444: Skip updateMatch entirely when no beforeLoad is defined to align with PR goal (fewer store updates)This early-bail branch still calls
pending()andresolve()which each executeupdateMatch(batched, but still a state write andfetchCountbump). The PR’s objective is to “skip beforeLoad and related store updates if options is not defined.” You can resolve the internal promise and return without any store mutations; the loader phase will take over settingisFetchingas needed.- // if there is no `beforeLoad` option, skip everything, batch update the store, return early - if (!route.options.beforeLoad) { - batch(() => { - pending() - resolve() - }) - return - } + // If there is no `beforeLoad` option, resolve and return early with no store writes + if (!route.options.beforeLoad) { + match._nonReactive.beforeLoadPromise?.resolve() + match._nonReactive.beforeLoadPromise = undefined + return + }Follow-up: This also avoids an extra
fetchCountincrement when nothing actually fetched.📜 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 891b55cdc40dafaaedb09d77ca783e32c512bc8c and 4fd8dfc7c2e22b780566744b1b5331970c66abbc.
📒 Files selected for processing (1)
packages/router-core/src/router.ts(4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/router-core/src/router.ts (3)
packages/router-core/src/utils.ts (2)
createControlledPromise(398-422)isPromise(477-485)
packages/router-core/src/route.ts (1)
BeforeLoadContextOptions(966-977)
packages/router-core/src/redirect.ts (1)
isRedirect(95-97)
⏰ 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 (2)
packages/router-core/src/router.ts (2)
2381-2400: Early surfacing of params/search validation errors is solidHandling
paramsErrorandsearchErrorup-front with explicit router codes (PARSE_PARAMS,VALIDATE_SEARCH) tightens control flow and simplifies downstream error handling. This looks correct and beneficial.
2729-2731: Good: only await pendingMinPromise when presentThis reduces unnecessary delay on the error path and keeps timing more predictable.
@@ -2914,3 +2932,8 @@29142932 for (let i = 0; i < innerLoadContext.matches.length; i++) {29152933 const beforeLoad = this.handleBeforeLoad(innerLoadContext, i)29162934 if (isPromise(beforeLoad)) await beforeLoad2935+ console.log(2936+ 'before load done',2937+ innerLoadContext.matches[i]!.id,2938+ this.getMatch(innerLoadContext.matches[i]!.id)?.context,2939+ )⚠️ Potential issue
Remove debug console.log from production code path
These logs execute during navigation and may spam consoles or leak route/match context (potentially sensitive). Please remove or guard behind a debug flag/ENV check.
- console.log( - 'before load done', - innerLoadContext.matches[i]!.id, - this.getMatch(innerLoadContext.matches[i]!.id)?.context, - )If you need runtime diagnostics, consider a
this.options.onDebug?.(...)hook orprocess.env.NODE_ENV !== 'production'guards.📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
🤖 Prompt for AI Agents
In packages/router-core/src/router.ts around lines 2935 to 2939 there is a console.log used for runtime debugging that runs on every navigation; remove this debug console.log from the production code path and either (a) delete the console.log call entirely, or (b) guard it so it only runs when debugging is enabled (for example wrap it in a check like process.env.NODE_ENV !== 'production' or call a provided hook such as this.options.onDebug?.(...) with the same payload). Ensure no raw route/match context is logged in production.✅ Addressed in commit 1532086
Actionable comments posted: 1
🧹 Nitpick comments (5)
packages/react-router/tests/store-updates-during-navigation.test.tsx (5)
84-86: Router options are appropriate; consider makingdefaultPreloadconfigurable per testSetting
defaultPreload: 'intent'globally works and is needed for the hover/focus scenario later. To reduce coupling across tests, consider acceptingdefaultPreloadas asetupoption so tests not exercising preloading can explicitly opt out. This can help reduce flakiness risk over time if event semantics evolve.
93-101: PreferfindByRoleover wrappinggetByRoleinwaitForfindBy*queries encapsulate waiting and read cleaner. This is functionally equivalent and a small readability win.Apply:
- fireEvent.click(link) - const title = await waitFor( - () => screen.getByRole('heading', { name: /Title$/ }), // matches /posts and /other and not found - ) + fireEvent.click(link) + const title = await screen.findByRole('heading', { name: /Title$/ }) // matches /posts and /other and not found
137-141: Optional: add a correctness assertion alongside the update-count metricIn addition to the update-count assertion, consider asserting the side-effect (redirect) to catch regressions where the redirect is swallowed but updates still occur. Example:
- expect(updates).toBe(6) + expect(updates).toBe(6) + // Optional: ensure we actually redirected + expect(router.state.location.pathname).toBe('/other')Note: If
preloadRouteis designed to not navigate, skip this assertion.
159-169: Good guardrails for minimal path; consider hardening against flakinessThe range assertion acknowledges timing variability. If this ever becomes noisy in CI, two knobs can help:
- Disable preloading for this test (see suggestion to make
defaultPreloadconfigurable). - Use fake timers around the 100–300ms pending thresholds to fully control scheduling.
If you want, I can sketch a minimal fake-timers pattern compatible with testing-library + React 18.
186-209: Preload-on-intent scenario is well captured; minor test ergonomicsThe focus+click sequence is appropriate for
'intent'preloading, and the assertion targets the metric you care about. Two tiny nits:- Prefer
findByRolefor readability, as above. - If you ever want to exercise hover intent specifically, you can also
fireEvent.mouseOver(link)(oruserEvent.hover) before click.
Apply:
- const title = await waitFor(() => - screen.getByRole('heading', { name: /Title$/ }), - ) + const title = await screen.findByRole('heading', { name: /Title$/ })📜 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 15320862e5b53e43e5d5887ab102be33acda32d5 and 8a7f95446be6508e3068da6adbd457d1d4feb8ec.
📒 Files selected for processing (1)
packages/react-router/tests/store-updates-during-navigation.test.tsx(4 hunks)
⏰ 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). (1)
- GitHub Check: Test
🔇 Additional comments (4)
packages/react-router/tests/store-updates-during-navigation.test.tsx (4)
2-8: Imports update looks goodThe test now consistently uses testing-library’s render/screen/waitFor and cleanup. No issues.
122-122: Expectation update matches the PR’s objectiveThe reduced update count (17 → 14) reflects the early bail-out when
beforeLoadis undefined. Looks good.
143-157: Solid coverage for synchronousbeforeLoadpathThis specifically validates the optimization delta when
beforeLoadis sync. No issues.
171-184: Covers not-found raised inbeforeLoadThis ensures the early not-found surfacing path doesn’t inflate updates. Looks correct.
packages/react-router/tests/store-updates-during-navigation.test.tsx line 16@@ -1,9 +1,16 @@11 import { afterEach, describe, expect, test, vi } from 'vitest'2-import { act, cleanup, render, screen, waitFor } from '@testing-library/react'2+import {3+ cleanup,4+ fireEvent,5+ render,6+ screen,7+ waitFor,8+} from '@testing-library/react'39 import {410 Link,511 Outlet,612 RouterProvider,713 createRootRoute,814 createRoute,915 createRouter,16+ notFound,💡 Verification agent
🧩 Analysis chain
Ensure the
notFoundexport is available from the public entryIf
notFoundis a new public API, verify it’s exported from the package entry and re-exported where this test imports it.Run this to confirm the export and its surface:
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Looking for notFound exports (direct or re-export):" rg -nP -C2 '(export\s+function\s+notFound\b)|(export\s+const\s+notFound\b)|(export\s*{\s*notFound\s*})' --type ts --glob '!**/node_modules/**' echo echo "Verifying createRouter options include defaultNotFoundComponent & defaultPreload:" rg -nP -C3 '\b(defaultNotFoundComponent|defaultPreload)\b' --type ts --glob '!**/node_modules/**'Length of output: 82102
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "=== Import section from the test file ===" sed -n '1,50p' packages/react-router/tests/store-updates-during-navigation.test.tsx echo echo "=== Re-exports of notFound in react-router public entry (index.ts) ===" rg -nP 'export\s+.*notFound' packages/react-router/src/index.ts || echo "No direct re-exports found in index.ts"Length of output: 1446
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "=== Files in packages/react-router/src ===" ls -1 packages/react-router/src echo echo "=== Looking for index.* files ===" find packages/react-router/src -maxdepth 1 -type f -name "index.*" || echo "No index.* files found" echo echo "=== Showing contents of any index.* file ===" for f in packages/react-router/src/index.*; do echo "---- $f ----" sed -n '1,200p' "$f" done 2>/dev/null || trueLength of output: 5057
Missing public export of
notFoundThe test in
packages/react-router/tests/store-updates-during-navigation.test.tsximportsnotFound, but it isn’t re-exported in the public entry atpackages/react-router/src/index.tsx. Add it to the export list:• File: packages/react-router/src/index.tsx
-export { - defer, - TSR_DEFERRED_PROMISE, - isMatch, - joinPaths, - cleanPath, - trimPathLeft, - trimPathRight, - trimPath, - resolvePath, - parsePathname, - interpolatePath, - matchPathname, - removeBasepath, - matchByPath, - encode, - decode, - rootRouteId, - defaultSerializeError, - defaultParseSearch, - defaultStringifySearch, - parseSearchWith, - stringifySearchWith, - escapeJSON, // SSR - pick, - functionalUpdate, - replaceEqualDeep, - isPlainObject, - isPlainArray, - deepEqual, - shallow, - createControlledPromise, - retainSearchParams, - stripSearchParams, -} from '@tanstack/router-core' +export { + defer, + TSR_DEFERRED_PROMISE, + isMatch, + joinPaths, + cleanPath, + trimPathLeft, + trimPathRight, + trimPath, + resolvePath, + parsePathname, + interpolatePath, + matchPathname, + removeBasepath, + matchByPath, + encode, + decode, + rootRouteId, + defaultSerializeError, + defaultParseSearch, + defaultStringifySearch, + parseSearchWith, + stringifySearchWith, + escapeJSON, // SSR + pick, + functionalUpdate, + replaceEqualDeep, + isPlainObject, + isPlainArray, + deepEqual, + shallow, + createControlledPromise, + retainSearchParams, + stripSearchParams, + notFound, +} from '@tanstack/router-core'📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
export { defer, TSR_DEFERRED_PROMISE, isMatch, joinPaths, cleanPath, trimPathLeft, trimPathRight, trimPath, resolvePath, parsePathname, interpolatePath, matchPathname, removeBasepath, matchByPath, encode, decode, rootRouteId, defaultSerializeError, defaultParseSearch, defaultStringifySearch, parseSearchWith, stringifySearchWith, escapeJSON, // SSR pick, functionalUpdate, replaceEqualDeep, isPlainObject, isPlainArray, deepEqual, shallow, createControlledPromise, retainSearchParams, stripSearchParams, notFound, } from '@tanstack/router-core'🤖 Prompt for AI Agents
packages/react-router/src/index.tsx (export list): The test imports `notFound` but it is not exported from the package entry; add a named export for `notFound` to the public export list in packages/react-router/src/index.tsx so it can be imported by tests and consumers. Ensure the exported identifier matches the internal symbol (or re-export from its source module), update the export list accordingly, and run the test suite to verify the import succeeds.- Disable preloading for this test (see suggestion to make
Sheraff(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
View your CI Pipeline Execution ↗ for commit 8a7f95446be6508e3068da6adbd457d1d4feb8ec
nx affected --targets=test:eslint,test:unit,tes...nx run-many --target=build --exclude=examples/*...☁️ Nx Cloud last updated this comment at
2025-08-16 08:41:06UTC