Skip to content
Source
Sign inSign up
TanStack/router

refactor(router-core): reduce buildLocation object allocations #4981

MergedSheraff(GitHub profile, opens in a new tab)merged 3 commits intomain fromrefs/pull/4981/headmerged 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

    2. Walkthrough

      buildLocation in packages/router-core/src/router.ts was 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

      Cohort / File(s)Summary
      Router core in-place mutations
      packages/router-core/src/router.ts
      Replace param/search immutability with in-place mutation using Object.assign; switch from map/forEach to for...of; pass mutated params into path interpolation and stringify/validation flows; behavior and public signatures unchanged.
      React router tests — capture params
      packages/react-router/tests/link.test.tsx
      Replace vi.fn spies with outer-scope capture variables; handlers assign structuredClone(params) to captures; assertions check captured values with toEqual instead of spy call checks.
      Solid router tests — capture params
      packages/solid-router/tests/link.test.tsx
      Same pattern as React tests: replace spies with capture variables, use structuredClone(params) in handlers, and assert on captured values.

      Sequence Diagram(s)

      sequenceDiagram
        participant Caller
        participant Router as buildLocation
        Caller->>Router: buildLocation(from, dest)
        Router->>Router: Create/assign nextParams (mutate via Object.assign)
        Router->>Router: Interpolate path using mutated nextParams
        Router->>Router: Stringify params (mutate nextParams further)
        Router->>Router: Validate/merge search into validatedSearch (mutate)
        Router-->>Caller: Return { pathname, search, params }

      Estimated code review effort

      🎯 3 (Moderate) | ⏱️ ~20 minutes

      Suggested labels

      package: react-router, package: solid-router

      Suggested reviewers

      • schiller-manuel

      Poem

      A hop and a bop through routes I go, I stitch params with a gentle flow. Object.assign, I patch and bind, loops hop along, no clones to find. Carrot paths gleam as routes align 🥕

      ✨ 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-build-location-reduce-object-allocation`

      🪧 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.
    3. View your CI Pipeline Execution ↗ for commit e4422ffcce13c82c3198083e4ff95959889c5e41

      CommandStatusDurationResult
      nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded1m 50sView ↗
      nx run-many --target=build --exclude=examples/*...✅ Succeeded1sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-08-17 16:21:46 UTC

    4. More templates

      @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@4981

      commit: e4422ff

    5. Actionable 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 bugs

      If a route's params.stringify accidentally returns a primitive or array, Object.assign may 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 allocations

      Minor 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 assumptions

      We’re now doing an in-place merge of fromParams, so:

      • Ensure no downstream code relies on the old fromParams object identity.
      • At runtime we special-case dest.params === false || dest.params === null but TS only lets you pass true | 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 !== fromParams for 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: Passing params: nextParams is safe and avoids an extra fallback allocation

      nextParams is 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 params

      Reusing the mutated nextParams for the final interpolation maintains behavior and avoids transient objects.

    6. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-router

    7. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: solid-router

    8. 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 fallback

      Use 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 fallback

      Replicate 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 tests

      structuredClone 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 mutation

      If 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 tests

      To 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 mutation

      Or 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 move

      Replacing 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 stringifyParams

      The 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 parseParams

      This ensures params arriving from the URL are captured before any mutation.


      3657-3658: LGTM: consistent capture pattern across tests

      Duplicating the capture pattern here keeps the test suite consistent.


      3696-3696: LGTM: assertion validates stringify input

      Capturing and asserting the pre-mutation input is correct and future-proof.


      3705-3705: LGTM: assertion validates parse input

      Asserting 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 tests

      Good change replacing vi.fn assertions with precise captured inputs.


      4064-4064: LGTM: verifies the exact object passed to stringifyParams

      Matches the new semantics and removes reliance on call-history mocks.


      4073-4073: LGTM: verifies the exact object passed to parseParams

      Correctly asserts the string form from the URL segment.


      4089-4091: LGTM: consistent capture variables in the nested params scenario

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

Sign in to join this conversation.