refactor(router-core): reduce buildLocation object allocations #4981
main fromrefs/pull/4981/head·merged by Sheraff(GitHub profile, opens in a new tab) When we can (and it's reasonable), it's always beneficial to reduce the number of objects we create in JS, so as to minimize the memory pressure and the GC work.
buildLocation gets called pretty often, so removing a few object allocations can be very beneficial (especially inside loops).
Also, from a purely "immediate performance" point of view, Object.assign tends to be faster than {...foo}.
Summary by CodeRabbit#
- Refactor
- Route parameter and search handling now use in-place updates to reduce allocations and streamline iteration/control flow; behavior and public API remain unchanged.
- Tests
- Updated tests to capture cloned parameter objects and assert on exact values rather than relying on mock call history, preventing mutation-related flakiness.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
View your CI Pipeline Execution ↗ for commit e4422ffcce13c82c3198083e4ff95959889c5e41
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded 1m 50s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 1s View ↗
☁️ Nx Cloud last updated this comment at
2025-08-17 16:21:46UTCMore 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@4981@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@4981@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@4981@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@4981@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@4981@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@4981@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@4981@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@4981@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@4981@tanstack/react-start-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-plugin@4981@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@4981@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@4981@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@4981@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@4981@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@4981@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@4981@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@4981@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@4981@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@4981@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@4981@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@4981@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@4981@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@4981@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@4981@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@4981@tanstack/solid-start-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-plugin@4981@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@4981@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@4981@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@4981@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@4981@tanstack/start-server-functions-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-client@4981@tanstack/start-server-functions-fetcher
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-fetcher@4981@tanstack/start-server-functions-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-server@4981@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@4981@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@4981@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@4981@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@4981commit:
e4422ffActionable comments posted: 0
🧹 Nitpick comments (3)
packages/router-core/src/router.ts (3)
1498-1504: Guard against non-object returns from params.stringify and reduce subtle bugsIf a route's
params.stringifyaccidentally returns a primitive or array,Object.assignmay behave unexpectedly (e.g., copy string indices). A tiny guard (dev-only warning) keeps behavior sane without hurting perf.Apply within this hunk:
- for (const route of destRoutes) { - const fn = - route.options.params?.stringify ?? route.options.stringifyParams - if (fn) { - Object.assign(nextParams, fn(nextParams)) - } - } + for (const route of destRoutes) { + const fn = + route.options.params?.stringify ?? route.options.stringifyParams + if (!fn) continue + const res = fn(nextParams) + if (res && typeof res === 'object' && !Array.isArray(res)) { + Object.assign(nextParams, res) + } else if (process.env.NODE_ENV !== 'production') { + // Help consumers catch mistakes early + console.warn( + 'params.stringify should return a plain object. Received:', + res, + ) + } + }
1521-1534: Prefer for..of + explicit typing for validatedSearch; maintains order and trims allocationsMinor polish that aligns with the PR’s intent and tightens types.
Apply within this hunk:
- const validatedSearch = {} - destRoutes.forEach((route) => { - if (route.options.validateSearch) { - try { - Object.assign( - validatedSearch, - validateSearch(route.options.validateSearch, { - ...validatedSearch, - ...nextSearch, - }), - ) - } catch { - // ignore errors here because they are already handled in matchRoutes - } - } - }) + const validatedSearch: Record<string, unknown> = {} + for (const route of destRoutes) { + const validator = route.options.validateSearch + if (!validator) continue + try { + Object.assign( + validatedSearch, + validateSearch(validator, { + ...validatedSearch, + ...nextSearch, + }) ?? undefined, + ) + } catch { + // ignore errors here because they are already handled in matchRoutes + } + }
1475-1484: Param merge now mutates the base object; check type allowances and caller assumptionsWe’re now doing an in-place merge of
fromParams, so:- Ensure no downstream code relies on the old
fromParamsobject identity. - At runtime we special-case
dest.params === false || dest.params === nullbut TS only lets you passtrue | Updater<…>. Let’s widen the types of all four fields to match the behavior.
Targets in packages/router-core/src/router.ts (around line 443 and inside
mask):export interface BuildNextOptions { to?: string | number | null - params?: true | Updater<unknown> + params?: true | false | null | Updater<unknown> - search?: true | Updater<unknown> + search?: true | false | Updater<unknown> - hash?: true | Updater<string> + hash?: true | false | Updater<string> - state?: true | NonNullableUpdater<ParsedHistoryState, HistoryState> + state?: true | false | NonNullableUpdater<ParsedHistoryState, HistoryState> mask?: { - params?: true | Updater<unknown> + params?: true | false | null | Updater<unknown> - search?: true | Updater<unknown> + search?: true | false | Updater<unknown> - hash?: true | Updater<string> + hash?: true | false | Updater<string> - state?: NonNullableUpdater<ParsedHistoryState, HistoryState> + state?: true | false | NonNullableUpdater<ParsedHistoryState, HistoryState> unmaskOnReload?: boolean } … }(optional) Double-check that no callers depend on
nextParams !== fromParamsfor change-detection.📜 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 72b65cfcca175f6397df854d229c14be06e57b61 and 163dce5b2d109a470b42e747322eca292ccd77a4.
📒 Files selected for processing (1)
packages/router-core/src/router.ts(3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/router-core/src/router.ts (2)
packages/router-core/src/utils.ts (1)
functionalUpdate(195-204)
packages/router-core/src/path.ts (1)
interpolatePath(371-481)
⏰ 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 (2)
packages/router-core/src/router.ts (2)
1486-1491: Passingparams: nextParamsis safe and avoids an extra fallback allocationnextParamsis always an object given the preceding logic, so dropping?? {}is correct and avoids a redundant allocation.
1507-1516: Second interpolation correctly uses the (now) stringified paramsReusing the mutated
nextParamsfor the final interpolation maintains behavior and avoids transient objects.- Ensure no downstream code relies on the old
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: solid-router
Actionable comments posted: 0
♻️ Duplicate comments (2)
packages/solid-router/tests/link.test.tsx (1)
3670-3670: Same note as above: avoid structuredClone or add a fallbackUse a shallow clone or a small helper to reduce dependency on structuredClone in the test environment.
Apply the same diffs suggested earlier for these lines as well.
Also applies to: 3677-3677
packages/react-router/tests/link.test.tsx (1)
4102-4102: Same note as above: avoid structuredClone or add a fallbackReplicate the shallow clone or helper approach here for robustness and lower overhead.
Also applies to: 4109-4109
🧹 Nitpick comments (2)
packages/solid-router/tests/link.test.tsx (1)
3607-3607: Prefer a shallow clone or add a fallback instead of structuredClone in testsstructuredClone might not exist in all CI environments; a shallow clone is sufficient here and avoids an unnecessary deep copy.
If you want to keep it minimal, switch to a shallow clone:
- parseParams = structuredClone(params) // clone object, because source will get mutated + parseParams = { ...params } // shallow clone to capture input before mutation- stringifyParams = structuredClone(params) // clone object, because source will get mutated + stringifyParams = { ...params } // shallow clone to capture input before mutationIf you prefer deep cloning, consider a tiny helper with a runtime fallback (added once per file) and use it in both places:
// near the top of the file const cloneParams = <T extends object>(p: T): T => typeof structuredClone === 'function' ? structuredClone(p) : { ...p }Then:
parseParams = cloneParams(params) stringifyParams = cloneParams(params)Please confirm your CI/test runners always expose structuredClone (Node ≥17 or a polyfill) if you keep the current approach.
Also applies to: 3614-3614
packages/react-router/tests/link.test.tsx (1)
4039-4039: Prefer a shallow clone or add a fallback instead of structuredClone in testsTo avoid depending on structuredClone availability (and to keep cloning lightweight in tests), use a shallow clone or a small helper.
Shallow clone option:
- parseParams = structuredClone(params) // clone object, because source will get mutated + parseParams = { ...params } // shallow clone to capture input before mutation- stringifyParams = structuredClone(params) // clone object, because source will get mutated + stringifyParams = { ...params } // shallow clone to capture input before mutationOr add once per file:
const cloneParams = <T extends object>(p: T): T => typeof structuredClone === 'function' ? structuredClone(p) : { ...p }Then:
parseParams = cloneParams(params) stringifyParams = cloneParams(params)Please confirm your CI Node/jsdom environment supports structuredClone if you keep it as-is.
Also applies to: 4046-4046
📜 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 163dce5b2d109a470b42e747322eca292ccd77a4 and e4422ffcce13c82c3198083e4ff95959889c5e41.
📒 Files selected for processing (2)
packages/react-router/tests/link.test.tsx(8 hunks)packages/solid-router/tests/link.test.tsx(8 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 (12)
packages/solid-router/tests/link.test.tsx (6)
3595-3596: LGTM: simpler input-capture over mocks is a good moveReplacing vi.fn call assertions with direct captured inputs makes the tests less brittle and validates actual values.
3632-3632: LGTM: assertion validates the raw input to stringifyParamsThe check now confirms the exact object given to stringify, aligning with the new in-place mutation semantics.
3641-3641: LGTM: assertion validates the raw input to parseParamsThis ensures params arriving from the URL are captured before any mutation.
3657-3658: LGTM: consistent capture pattern across testsDuplicating the capture pattern here keeps the test suite consistent.
3696-3696: LGTM: assertion validates stringify inputCapturing and asserting the pre-mutation input is correct and future-proof.
3705-3705: LGTM: assertion validates parse inputAsserting the string form received by parseParams improves test fidelity.
packages/react-router/tests/link.test.tsx (6)
4027-4028: LGTM: direct input capture simplifies the testsGood change replacing vi.fn assertions with precise captured inputs.
4064-4064: LGTM: verifies the exact object passed to stringifyParamsMatches the new semantics and removes reliance on call-history mocks.
4073-4073: LGTM: verifies the exact object passed to parseParamsCorrectly asserts the string form from the URL segment.
4089-4091: LGTM: consistent capture variables in the nested params scenarioKeeps the approach uniform across both parse/stringify locations.
4128-4128: LGTM: assertion for stringify input (params.stringify path)Confirms we’re capturing inputs at the right boundary.
4137-4137: LGTM: assertion for parse input (params.parse path)Validates the expected shape and type before any internal mutation.
Sheraff(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Walkthrough#
buildLocation in
packages/router-core/src/router.tswas refactored to perform in-place mutations (via Object.assign) for params and search objects, replace map/forEach with for...of loops, and propagate the mutated params into path interpolation and stringify/validation steps. No public API signatures changed.Changes#
packages/router-core/src/router.tsObject.assign; switch from map/forEach tofor...of; pass mutated params into path interpolation and stringify/validation flows; behavior and public signatures unchanged.packages/react-router/tests/link.test.tsxvi.fnspies with outer-scope capture variables; handlers assignstructuredClone(params)to captures; assertions check captured values withtoEqualinstead of spy call checks.packages/solid-router/tests/link.test.tsxstructuredClone(params)in handlers, and assert on captured values.Sequence Diagram(s)#
Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~20 minutes
Suggested labels#
package: react-router,package: solid-routerSuggested 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#