fix(router-core): params.parse should run as minimally as possible #5124
main fromrefs/pull/5124/head·merged by nlynzaad(GitHub profile, opens in a new tab) resolves #5123 and adds checks to tests to ensure this runs as minimally as possible
Summary by CodeRabbit#
- Performance
- Reuses existing route matches to reduce redundant param parsing and stabilize navigation/loading behavior.
- Tests
- Updated tests to match the new postId param shape, navigation paths, and parameter displays; added mocks to verify param parsing calls.
- 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
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: solid-router
View your CI Pipeline Execution ↗ for commit 4858951d6cbd50449f512950fcb98f74179a08f1
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded 1m 57s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 3s View ↗
☁️ Nx Cloud last updated this comment at
2025-09-11 13:24:23UTCMore 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@5124@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5124@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5124@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5124@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5124@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5124@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5124@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5124@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5124@tanstack/react-start-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-plugin@5124@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5124@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5124@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5124@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5124@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5124@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5124@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5124@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5124@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5124@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5124@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5124@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5124@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5124@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5124@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5124@tanstack/solid-start-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-plugin@5124@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5124@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5124@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5124@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5124@tanstack/start-server-functions-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-client@5124@tanstack/start-server-functions-fetcher
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-fetcher@5124@tanstack/start-server-functions-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-server@5124@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5124@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5124@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5124@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5124commit:
4858951Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 9a86563ae032480764b51a53015ded3742dce20f and 9ad73692f5b83332cb9d6557934733d1761e0adf.
📒 Files selected for processing (3)
packages/react-router/tests/useParams.test.tsx(5 hunks)packages/router-core/src/router.ts(2 hunks)packages/solid-router/tests/useParams.test.tsx(5 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). (2)
- GitHub Check: Test
- GitHub Check: Preview
🔇 Additional comments (5)
packages/router-core/src/router.ts (3)
1200-1209: LGTM! Optimization correctly reuses existing match dataThe implementation correctly prevents redundant parsing by checking for an existing match and reusing its
_strictParams. This directly addresses the issue where params.parse was being called unnecessarily.
1214-1239: Robust implementation of conditional parameter parsingThe logic correctly:
- Reuses
_strictParamsfrom existing matches when available - Falls back to
interpolatePathResult.usedParamsfor new matches - Only invokes
params.parsewhen there's no existing match and parsing is configured - Properly handles errors with the new
paramsErrorvariable
This ensures params.parse runs minimally as intended.
1241-1241: Good use of Object.assign for parameter mergingUsing
Object.assign(routeParams, strictParams)efficiently merges the strict parameters into the route parameters object.packages/react-router/tests/useParams.test.tsx (2)
73-85: Test correctly validates params.parse minimizationThe test setup appropriately:
- Adds console.log() to track parse invocations
- Converts the parse function to work with string params (postId as '1' or '2')
- Updates the loader to use
parseInt(params.postId)for type conversion
This validates that the parse function receives the correct string type as expected per issue #5123.
186-250: Comprehensive test assertions for parse invocation trackingThe test thoroughly validates the optimization by:
- Clearing and checking console spy at each navigation step
- Asserting specific call counts to ensure parse runs minimally
- Verifying the correct param values are displayed
Excellent test coverage for the PR objectives.
@@ -70,5 +70,9 @@7070 const postRoute = createRoute({7171 getParentRoute: () => postCategoryRoute,7272 path: '$postId',73+ loader: ({ params }) => {74+ return { post: posts.find((post) => post.id === parseInt(params.postId)) }75+ },7376 params: {7477 parse: (params) => {78+ console.log()🛠️ Refactor suggestion
Remove empty console.log() statement
Same as in the Solid router test - the empty console.log() should have a descriptive message.
- console.log() + console.log('params.parse called')📝 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.
console.log('params.parse called')🤖 Prompt for AI Agents
In packages/react-router/tests/useParams.test.tsx around line 78 there's an empty console.log() call; replace it with a meaningful message (e.g., console.log('useParams test: verifying param parsing for route X') or another context-appropriate description) or remove it entirely if logging isn't needed, ensuring tests remain deterministic and any retained log includes clear context for debugging.@@ -72,3 +72,4 @@7272 path: '$postId',7373 params: {7474 parse: (params) => {75+ console.log()🛠️ Refactor suggestion
Remove empty console.log() statement
The console.log() call is empty and only used for test counting. Consider using a more descriptive log message or a dedicated test spy function.
- console.log() + console.log('params.parse called')📝 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.
console.log('params.parse called')🤖 Prompt for AI Agents
In packages/solid-router/tests/useParams.test.tsx around line 75, there is an empty console.log() used only for test counting; remove the empty call and either replace it with a descriptive log message (e.g., indicating which test reached this point) or, preferably, replace the counting mechanism with a dedicated test spy/assertion (e.g., use a test double or assertion to track calls) so the test no longer relies on side-effect console output.Actionable comments posted: 0
♻️ Duplicate comments (2)
packages/solid-router/tests/useParams.test.tsx (1)
27-27: Resolved: replaced no-op console.log with a vi.fn spy.Good switch to a proper spy for deterministic assertions.
packages/react-router/tests/useParams.test.tsx (1)
27-27: Resolved: replaced no-op console.log with a vi.fn spy.Nice cleanup; mirrors the Solid test approach.
🧹 Nitpick comments (9)
packages/solid-router/tests/useParams.test.tsx (4)
75-82: Avoid defaulting to '2' in parse; use an explicit map or pass-through.Defaulting any non-'one' value to '2' can mask issues and inflate parse counts. Map known values and otherwise pass through.
- parse: (params) => { - mockedfn() - return { - ...params, - postId: params.postId === 'one' ? '1' : '2', - } - }, + parse: (params) => { + mockedfn() + const idMap = { one: '1', two: '2' } as const + return { ...params, postId: idMap[params.postId] ?? params.postId } + },
85-85: Specify radix for parseInt.Be explicit to avoid edge cases with leading zeros.
- post: posts.find((post) => post.id === parseInt(params.postId)), + post: posts.find((post) => post.id === parseInt(params.postId, 10)),
191-191: Parse call-count assertions are brittle.Exact-call assertions may fail with benign internal changes. Prefer asserting upper bounds and/or validating parse inputs.
Example adjustments:
- Upper bound:
expect(mockedfn.mock.calls.length).toBeLessThanOrEqual(N) - Validate inputs (Solid): capture params passed into
parsewith a vi.fn wrapper and assertpostIdis 'one'/'two' on respective navigations.
Also applies to: 214-214, 225-225, 247-247
184-184: Reduce repetition for mock resets.Extract a helper or reset in a scoped utility to keep the test flow concise.
- mockedfn.mockClear() + // helper + const resetParseSpy = () => mockedfn.mockClear() + resetParseSpy()Also applies to: 193-193, 217-217, 227-227
packages/react-router/tests/useParams.test.tsx (5)
74-77: Specify radix for parseInt in loader.- loader: ({ params }) => { - return { post: posts.find((post) => post.id === parseInt(params.postId)) } - }, + loader: ({ params }) => { + return { post: posts.find((post) => post.id === parseInt(params.postId, 10)) } + },
78-85: Avoid defaulting to '2' in parse; use an explicit map or pass-through.- params: { - parse: (params) => { - mockedfn() - return { - ...params, - postId: params.postId === 'one' ? '1' : '2', - } - }, - }, + params: { + parse: (params) => { + mockedfn() + const idMap = { one: '1', two: '2' } as const + return { ...params, postId: idMap[params.postId] ?? params.postId } + }, + },
177-177: Use asynchronousactcorrectly with promises.Wrap the awaited call in an async
actblock to avoid warnings.- await act(() => router.load()) + await act(async () => { + await router.load() + })
186-186:actaround sync clicks doesn’t needawait; make it consistently sync.Keeps intent clear and avoids implying asynchrony where there is none.
- await act(() => fireEvent.click(firstCategoryLink)) + act(() => { + fireEvent.click(firstCategoryLink) + })Apply similarly to the other click handlers in this file.
Also applies to: 195-195, 220-220, 230-230
192-192: Parse call-count assertions may be too strict.Assert upper bounds and/or validate the params received by parse to reduce brittleness while still guarding “minimal” execution.
Example:
expect(mockedfn.mock.calls.length).toBeLessThanOrEqual(N) // or // const parsePost = vi.fn((p) => ({...})) // expect(parsePost).toHaveBeenLastCalledWith(expect.objectContaining({ postId: 'one' }))Also applies to: 216-216, 227-227, 249-249
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 9ad73692f5b83332cb9d6557934733d1761e0adf and 4858951d6cbd50449f512950fcb98f74179a08f1.
📒 Files selected for processing (2)
packages/react-router/tests/useParams.test.tsx(5 hunks)packages/solid-router/tests/useParams.test.tsx(5 hunks)
🔇 Additional comments (2)
packages/solid-router/tests/useParams.test.tsx (1)
123-125: LGTM: relativeto="./$postId"with params.This properly defers encoding to the router and avoids manual string interpolation.
packages/react-router/tests/useParams.test.tsx (1)
124-126: LGTM:to="./$postId"with params.Removes brittle string interpolation and leverages route semantics.
- Upper bound:
nlynzaad(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Walkthrough#
Reworks router-core match construction to reuse existing match _strictParams and only run params.parse when necessary, attaching any parse error to the match. Updates React and Solid tests to use string
postIdparams, adjust loaders toparseInt(params.postId), change links toto="./$postId"withparams, and addvi-based mocking for parse instrumentation.Changes#
packages/router-core/src/router.tsmatchIdearlier, lookupexistingMatchandpreviousMatch; reuseexistingMatch._strictParamswhen available; runparams.parseonly when there is no existing match; attachparamsErrorto match instead of earlier parseErrors aggregation; mergestrictParamsintorouteParams.packages/react-router/tests/useParams.test.tsxvi, addvi.fn()mock; replace numericidparam with stringpostId; updateparams.parse/stringify, loader usesparseInt(params.postId); links changed toto="./$postId"withparams; UI/test assertions updated to checkparam_postId_value; removedId_Paramdisplay.packages/solid-router/tests/useParams.test.tsxvi, usevi.fn()mock, switch topostIdstring param, updateparse/stringify, loader usesparseInt(params.postId), links useto="./$postId"withparams, and tests assert onparam_postId_valueand navigation paths.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs#
match._strictParams.router-core/src/router.ts, touching the same parsing/error handling area.getMatch/match reuse that are conceptually related to the current match identity and reuse changes.Suggested reviewers#
Pre-merge checks (4 passed, 1 warning)#
❌ Failed checks (1 warning)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (4 passed)
Poem#
Tip
👮 Agentic pre-merge checks are now available in preview!
Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.
Please see the documentation for more information.
Example:
Please share your feedback with us on this Discord post.
✨ Finishing touches
🧪 Generate unit tests
Comment `@coderabbitai help` to get the list of available commands and usage tips.