From 663a9045ededf11045b02b24dd943d5fe9b5549a Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 20 Mar 2026 23:13:47 +0100 Subject: [PATCH 1/5] perf: avoid rebuilding React Link locations on unrelated updates Teach router-core to expose internal Link dependency metadata so React can reuse cached next locations during search-only churn. Add a focused benchmark and investigation notes so the targeted win can be measured against main. --- benchmarks/client-nav/react/app.tsx | 49 +++- benchmarks/client-nav/react/setup.ts | 34 ++- benchmarks/client-nav/react/speed.bench.ts | 64 ++--- link-performance-investigation.md | 272 +++++++++++++++++++++ packages/react-router/src/link.tsx | 225 ++++++++++++++++- packages/react-router/tests/link.test.tsx | 97 ++++++++ packages/router-core/src/RouterProvider.ts | 1 + packages/router-core/src/router.ts | 87 ++++++- 8 files changed, 771 insertions(+), 58 deletions(-) create mode 100644 link-performance-investigation.md diff --git a/benchmarks/client-nav/react/app.tsx b/benchmarks/client-nav/react/app.tsx index d26aba6e91..82d23f0727 100644 --- a/benchmarks/client-nav/react/app.tsx +++ b/benchmarks/client-nav/react/app.tsx @@ -11,6 +11,8 @@ import { } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' +export type Scenario = 'default' | 'static-search-links' + function runPerfSelectorComputation(seed: number) { let value = Math.trunc(seed) | 0 @@ -22,6 +24,7 @@ function runPerfSelectorComputation(seed: number) { } const selectors = Array.from({ length: 20 }, (_, index) => index) +const staticSearchLinkIds = Array.from({ length: 200 }, (_, index) => index) function Params() { const params = useParams({ @@ -49,6 +52,18 @@ function Links() { ) } +function StaticSearchLinks(props: { linkId: number }) { + return ( + + Link + + ) +} + function Root() { return ( <> @@ -66,20 +81,34 @@ function Root() { ) } -const rootRoute = createRootRoute({ - component: Root, -}) +function StaticSearchLinksRoot() { + return ( + <> + {staticSearchLinkIds.map((linkId) => ( + + ))} + + + ) +} -const route = createRoute({ - getParentRoute: () => rootRoute, - path: '/$id', - component: () =>
, -}) +export function mountTestApp( + container: Element, + scenario: Scenario = 'default', +) { + const rootRoute = createRootRoute({ + component: scenario === 'default' ? Root : StaticSearchLinksRoot, + }) + + const route = createRoute({ + getParentRoute: () => rootRoute, + path: scenario === 'default' ? '/$id' : '/links', + component: () =>
, + }) -export function mountTestApp(container: Element) { const router = createRouter({ history: createMemoryHistory({ - initialEntries: ['/0'], + initialEntries: [scenario === 'default' ? '/0' : '/links'], }), scrollRestoration: true, routeTree: rootRoute.addChildren([route]), diff --git a/benchmarks/client-nav/react/setup.ts b/benchmarks/client-nav/react/setup.ts index bc51cdb53b..2ca0c1b37a 100644 --- a/benchmarks/client-nav/react/setup.ts +++ b/benchmarks/client-nav/react/setup.ts @@ -4,7 +4,9 @@ import type * as App from './app' const appModulePath = './dist/app.js' const { mountTestApp } = (await import(appModulePath)) as typeof App -export function setup() { +type Scenario = App.Scenario + +export function setup(scenario: Scenario = 'default') { if (process.env.NODE_ENV !== 'production') { console.warn( 'client-nav benchmark is running without NODE_ENV=production; React dev overhead will dominate results.', @@ -21,7 +23,7 @@ export function setup() { container = document.createElement('div') document.body.append(container) - const { router, unmount: dispose } = mountTestApp(container) + const { router, unmount: dispose } = mountTestApp(container, scenario) unmount = dispose let resolve: () => void = () => {} unsub = router.subscribe('onRendered', () => resolve()) @@ -32,17 +34,25 @@ export function setup() { router.navigate(opts) }) - next = () => { - const nextId = id++ + next = + scenario === 'default' + ? () => { + const nextId = id++ - return navigate({ - to: '/$id', - params: { id: nextId }, - // update search every 2 navigations, to still test them, but also measure the impact of granular re-rendering - search: { id: Math.floor(nextId / 2) }, - replace: true, - }) - } + return navigate({ + to: '/$id', + params: { id: nextId }, + // update search every 2 navigations, to still test them, but also measure the impact of granular re-rendering + search: { id: Math.floor(nextId / 2) }, + replace: true, + }) + } + : () => + navigate({ + to: '/links', + search: { id: id++ }, + replace: true, + }) await router.load() } diff --git a/benchmarks/client-nav/react/speed.bench.ts b/benchmarks/client-nav/react/speed.bench.ts index fcc15b5fbc..6c594b1f2f 100644 --- a/benchmarks/client-nav/react/speed.bench.ts +++ b/benchmarks/client-nav/react/speed.bench.ts @@ -1,34 +1,42 @@ import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' +function registerBenchmark(name: string, test: ReturnType) { + describe(name, () => { + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( + name, + async () => { + for (let i = 0; i < 10; i++) { + await test.tick() + } + }, + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, + ) + }) +} + describe('client-nav', () => { - const test = setup() - - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( - 'client-side navigation loop (react)', - async () => { - for (let i = 0; i < 10; i++) { - await test.tick() - } - }, - { - warmupIterations: 100, - time: 10_000, - setup: test.before, - teardown: test.after, - }, + registerBenchmark('client-side navigation loop (react)', setup()) + registerBenchmark( + 'client-side navigation loop with static search links (react)', + setup('static-search-links'), ) }) diff --git a/link-performance-investigation.md b/link-performance-investigation.md new file mode 100644 index 0000000000..5425ea2f5c --- /dev/null +++ b/link-performance-investigation.md @@ -0,0 +1,272 @@ +# Link Performance Investigation + +Date: 2026-03-20 + +## Goal + +Investigate how to reduce unnecessary `Link` work when the current router location changes, especially when `location.search` changes but a link's next location does not actually depend on current search. + +The main target is React, because React `Link` rerenders are the expensive case. Solid and Vue still matter for avoiding wasted `buildLocation` calls, but rerender pressure is much lower there. + +## What I Read + +- Adapter `Link` implementations: + - `packages/react-router/src/link.tsx` + - `packages/solid-router/src/link.tsx` + - `packages/vue-router/src/link.tsx` +- Router-core location building and matching: + - `packages/router-core/src/router.ts` + - `packages/router-core/src/location.ts` + - `packages/router-core/src/path.ts` + - `packages/router-core/src/RouterProvider.ts` +- React location update lifecycle: + - `packages/react-router/src/Transitioner.tsx` +- Existing and new benchmarks: + - `benchmarks/client-nav/react/app.tsx` + - `benchmarks/client-nav/react/setup.ts` + - `benchmarks/client-nav/react/speed.bench.ts` + +## What We Know + +- `buildLocation` is expensive. +- The old `Link` behavior rebuilt `next` whenever the full current location changed. +- Many links do not need current `location.search` to compute `next`. +- Most users do not set `activeOptions={{ includeSearch: false }}`. +- For the common default `includeSearch: true` case, skipping `buildLocation` can still help even if React still rerenders to recompute `isActive`. + +## Lifecycle: History -> Router -> Link -> buildLocation + +1. Browser/history location changes. +2. React `Transitioner` subscribes history to `router.load()`. +3. `router.beforeLoad()` updates `router.stores.location` early, before all route loading finishes. +4. Every `Link` that subscribes to `router.stores.location` gets that update. +5. If a `Link` decides the new location matters, React rerenders the component. +6. During render, `Link` calls `router.buildLocation(...)` to compute `next`. +7. `buildLocation` does all of the following: + - resolves the current route context from the current location + - computes `from` / `to` + - resolves and stringifies params + - matches destination routes + - applies search middleware / legacy search filters / validateSearch + - computes hash, state, href, publicHref, and masked location +8. `Link` then computes `href` and `isActive` from the current location and the built `next` location. + +## How `location`, `buildLocation`, and `Link` Fit Together + +- `router.stores.location` is the reactive trigger. +- `Link` is the consumer that decides whether a location update matters. +- `buildLocation` is the expensive derivation step used to compute `next`. +- The key optimization problem is not only "what does a link depend on?". +- The real problem is "how do we know the dependency set without spending enough work to cancel out the win?". + +## Attempt 1: Adapter-Local Dependency Analysis in React/Solid/Vue + +### Shape + +- Split each adapter into two subscriptions: + - one for `next` / `buildLocation` + - one for `isActive` +- Add adapter-local helper logic to infer whether current pathname/search/hash/state matter. +- Duplicate route matching logic in each adapter to decide whether current search matters because of destination search middleware. + +### What Worked + +- Narrow tests passed. +- Search-only changes could skip `buildLocation` for static-search links. + +### What Failed + +- Too much duplicated code across adapters. +- Bundle size increased noticeably. +- The existing mixed client-nav benchmark did not improve. +- React became slightly slower in the broad benchmark. + +### Conclusion + +This approach was the wrong abstraction boundary. It moved expensive reasoning into adapter space and duplicated route analysis three times. + +## Attempt 2: React-Only Single Subscription + Core Dependency Metadata + +### Shape + +- Revert Solid and Vue back to the simpler baseline behavior. +- Keep React-focused optimization only. +- Add an internal `_collectLocationDeps` option to `buildLocation`. +- While `buildLocation` is already resolving the destination route branch, compute a tiny dependency bitmask for the fields that matter: + - pathname / current route context + - search + - hash + - state +- In React `Link`: + - keep a single `useStore` subscription to `router.stores.location` + - cache the previous built `next` location plus the dependency bitmask + - rebuild only when a location change intersects the cached dependency bitmask + - still rerender when active-state inputs change, but reuse cached `next` + +### Why This Is Better + +- No duplicated route matching in adapter code. +- Only one React store subscription. +- Search dependency is determined from the same work `buildLocation` already does. +- The common default case can still skip `buildLocation` even when `isActive` must be recomputed. + +## Important Correctness Fix During Investigation + +While rerunning affected unit tests, `packages/react-router/tests/link.test.tsx` surfaced a regression in the existing test: + +- `keeps a relative link active when changing inherited params (issue #5655)` + +Cause: + +- The first dependency-mask version missed the fact that omitted `params` still inherit current params when `nextTo` contains path params. + +Fix: + +- Mark pathname as a dependency when params are inherited/merged and the resolved `nextTo` path template contains `$` params. + +## What Is Currently In Code + +- React-only optimization: + - `packages/react-router/src/link.tsx` +- Core dependency metadata support: + - `packages/router-core/src/router.ts` + - `packages/router-core/src/RouterProvider.ts` +- New React benchmark scenario: + - `benchmarks/client-nav/react/app.tsx` + - `benchmarks/client-nav/react/setup.ts` + - `benchmarks/client-nav/react/speed.bench.ts` +- React tests: + - `packages/react-router/tests/link.test.tsx` + +Solid and Vue were intentionally restored to the baseline implementation for now. + +## Benchmark Design + +### Existing Benchmark + +The original `client-nav` benchmark changes pathname every navigation and changes search every other navigation. That is a broad benchmark, but it does not isolate the search-only optimization target. + +### New Benchmark + +Added a second React scenario: `client-side navigation loop with static search links (react)`. + +Shape: + +- Stable pathname: `/links` +- Current search changes every tick +- 200 rendered `Link`s +- Each `Link` has static `search={{ linkId: ... }}` + +This isolates the intended search-only invalidation case. + +## Benchmarks I Ran + +### Validation / Build Commands + +- `CI=1 NX_DAEMON=false pnpm nx run @tanstack/react-router:test:eslint --outputStyle=stream --skipRemoteCache` +- `CI=1 NX_DAEMON=false pnpm nx affected --target=test:eslint --exclude=examples/**,e2e/** --outputStyle=stream --skipRemoteCache` +- `CI=1 NX_DAEMON=false pnpm nx affected --target=test:types --exclude=examples/** --outputStyle=stream --skipRemoteCache` +- `CI=1 NX_DAEMON=false pnpm nx affected --target=test:unit --exclude=examples/**,e2e/** --outputStyle=stream --skipRemoteCache` +- `CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:react --outputStyle=stream --skipRemoteCache` +- `CI=1 NX_DAEMON=false pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache` + +### Focused React Tests + +- `CI=1 NX_DAEMON=false pnpm nx run @tanstack/react-router:test:unit --outputStyle=stream --skipRemoteCache -- tests/link.test.tsx -t "does not rebuild static next locations on unrelated search changes"` +- `CI=1 NX_DAEMON=false pnpm nx run @tanstack/react-router:test:unit --outputStyle=stream --skipRemoteCache -- tests/link.test.tsx -t "keeps a relative link active when changing inherited params \(issue #5655\)"` + +### Main Comparison Method + +- Created a temporary detached worktree at `origin/main` +- Installed deps there +- Ran the same React benchmarks on `main` +- Compared current branch vs `main` + +## Measurements + +### Mixed React client-nav benchmark + +Current implementation vs `main`: + +- `main`: `37.94 hz`, mean `26.36 ms` +- current: `37.12 hz`, mean `26.94 ms` +- Result: roughly flat to slightly worse (`-2.2%` throughput) + +Interpretation: + +- The mixed benchmark is still dominated by cases where pathname changes and links legitimately need work. +- The new optimization does not materially help this broad scenario yet. + +### Search-only benchmark, with `activeOptions={{ includeSearch: false }}` + +Current implementation vs `main`: + +- `main`: `15.93 hz`, mean `62.76 ms` +- current: `26.33 hz`, mean `37.98 ms` +- Result: `+65.2%` throughput, `-39.5%` mean time + +Interpretation: + +- This is the ideal case: current search changes do not matter to `next` or `isActive`. +- The optimization skips both `buildLocation` and React rerender work. + +### Search-only benchmark, default `includeSearch: true` + +Measured by temporarily removing `activeOptions={{ includeSearch: false }}` from the new benchmark. + +Current implementation vs `main`: + +- `main`: `17.36 hz`, mean `57.60 ms` +- current: `18.36 hz`, mean `54.47 ms` +- Result: `+5.8%` throughput, `-5.4%` mean time + +Interpretation: + +- The gain is still real, but much smaller. +- Default `includeSearch: true` means React `Link` usually still rerenders to recompute `isActive` when current search changes. +- The remaining win comes from reusing cached `next` and skipping `buildLocation`. + +### Bundle size + +Current implementation vs `main`: + +- `react-router.minimal`: `90682 -> 91453 gzip` (`+771 B`, `+0.85%`) +- `react-router.full`: `93928 -> 94692 gzip` (`+764 B`, `+0.81%`) + +Interpretation: + +- The core-assisted React-only approach is still larger than `main`, but much better than the original three-adapter duplicated approach. + +## What Worked + +- Moving dependency analysis into `buildLocation` instead of duplicating route matching in adapters. +- Returning a tiny internal dependency mask instead of a large metadata object. +- Using one React store subscription and cached built locations. +- Adding a search-only benchmark that actually measures the intended optimization target. + +## What Did Not Work + +- Per-adapter duplicated dependency analysis. +- Two subscriptions per `Link` in all adapters. +- Expecting the broad mixed client-nav benchmark to show the targeted search-only win. + +## Current Understanding + +- The optimization target is real. +- The common-case default `includeSearch: true` still benefits, but only modestly, because React usually still has to rerender for active-state changes. +- The biggest win appears when search changes affect neither `next` nor `isActive`. +- The current mixed benchmark suggests there is still a larger amount of unavoidable pathname-driven work in the general case. + +## Open Questions / Next Steps + +1. Can active-state search dependency become narrower for common static-search links, even when `includeSearch` stays at its default `true`? +2. Can the dependency mask be compressed or inferred with less emitted code to reduce the remaining React bundle increase? +3. Is there a cheap way to distinguish "needs exact current search" from "only needs to know whether current search exists" in more common cases? +4. Should the same core-assisted pattern eventually be extended to Solid and Vue, or is React the only adapter worth optimizing at this level? + +## Practical Status + +- React-only optimization is implemented and benchmarked. +- Narrow correctness regressions are covered by tests. +- Affected eslint, affected type tests, and affected unit tests pass. +- A draft PR is appropriate because the targeted benchmark win is strong, but the broad benchmark remains flat/slightly worse and the bundle is still somewhat larger than `main`. diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index 3f0dc83a22..6b61fa8ad6 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -19,6 +19,7 @@ import type { AnyRouter, Constrain, LinkOptions, + ParsedLocation, RegisteredRouter, RoutePaths, } from '@tanstack/router-core' @@ -396,18 +397,76 @@ export function useLinkProps< ) // eslint-disable-next-line react-hooks/rules-of-hooks - const currentLocation = useStore( - router.stores.location, - (l) => l, - (prev, next) => prev.href === next.href, + const buildLocationRef = React.useRef(null) + // eslint-disable-next-line react-hooks/rules-of-hooks + const activeLocationDepsRef = React.useRef( + NO_ACTIVE_LOCATION_DEPS, ) // eslint-disable-next-line react-hooks/rules-of-hooks - const next = React.useMemo(() => { - const opts = { _fromLocation: currentLocation, ..._options } - return router.buildLocation(opts as any) + const locationStateEqual = React.useCallback( + (prev: ParsedLocation, next: ParsedLocation) => { + const buildLocation = buildLocationRef.current + + if ( + didLocationChange( + prev, + next, + buildLocation?.deps ?? BUILD_LOCATION_DEP_ALL, + ) || + didActiveLocationChange(prev, next, activeLocationDepsRef.current) + ) { + return false + } + + return true + }, + [], + ) + + // eslint-disable-next-line react-hooks/rules-of-hooks + const currentLocation = useStore( + router.stores.location, + (l) => l, + locationStateEqual, + ) + + // eslint-disable-next-line react-hooks/rules-of-hooks + const buildLocation = React.useMemo(() => { + const previousBuildLocation = buildLocationRef.current + + if ( + previousBuildLocation && + previousBuildLocation.router === router && + previousBuildLocation.options === _options && + !didLocationChange( + previousBuildLocation.location, + currentLocation, + previousBuildLocation.deps, + ) + ) { + return previousBuildLocation + } + + const next = router.buildLocation({ + _collectLocationDeps: true, + _fromLocation: currentLocation, + ..._options, + } as any) + + return { + router, + location: currentLocation, + next, + deps: _options._fromLocation + ? BUILD_LOCATION_DEP_NONE + : getBuildLocationDeps(next), + options: _options, + } }, [router, currentLocation, _options]) + const next = buildLocation.next + // Use publicHref - it contains the correct href for display // When a rewrite changes the origin, publicHref is the full URL // Otherwise it's the origin-stripped path @@ -461,6 +520,27 @@ export function useLinkProps< return undefined }, [to, hrefOption, router.protocolAllowlist]) + // eslint-disable-next-line react-hooks/rules-of-hooks + const activeLocationDeps = React.useMemo( + () => + getActiveLocationDeps( + activeOptions, + { + hash: next.hash, + pathname: next.pathname, + search: next.search, + }, + !!externalLink, + ), + [activeOptions, externalLink, next.hash, next.pathname, next.search], + ) + + // eslint-disable-next-line react-hooks/rules-of-hooks + React.useLayoutEffect(() => { + buildLocationRef.current = buildLocation + activeLocationDepsRef.current = activeLocationDeps + }, [activeLocationDeps, buildLocation]) + // eslint-disable-next-line react-hooks/rules-of-hooks const isActive = React.useMemo(() => { if (externalLink) return false @@ -725,6 +805,41 @@ const intersectionObserverOptions: IntersectionObserverInit = { rootMargin: '100px', } +type BuildLocationState = { + router: AnyRouter + location: ParsedLocation + next: ParsedLocation + deps: number + options: unknown +} + +type ActiveLocationDeps = { + deps: number + ignoreUndefined: boolean + searchMode: number +} + +const BUILD_LOCATION_DEP_NONE = 0 +const BUILD_LOCATION_DEP_PATHNAME = 1 << 0 +const BUILD_LOCATION_DEP_SEARCH = 1 << 1 +const BUILD_LOCATION_DEP_HASH = 1 << 2 +const BUILD_LOCATION_DEP_STATE = 1 << 3 +const BUILD_LOCATION_DEP_ALL = + BUILD_LOCATION_DEP_PATHNAME | + BUILD_LOCATION_DEP_SEARCH | + BUILD_LOCATION_DEP_HASH | + BUILD_LOCATION_DEP_STATE + +const ACTIVE_LOCATION_SEARCH_NONE = 0 +const ACTIVE_LOCATION_SEARCH_FULL = 1 +const ACTIVE_LOCATION_SEARCH_HAS_ENTRIES = 2 + +const NO_ACTIVE_LOCATION_DEPS: ActiveLocationDeps = { + deps: BUILD_LOCATION_DEP_NONE, + ignoreUndefined: true, + searchMode: ACTIVE_LOCATION_SEARCH_NONE, +} + const composeHandlers = (handlers: Array>) => (e: React.SyntheticEvent) => { @@ -759,6 +874,102 @@ function isSafeInternal(to: unknown) { return zero === 46 // '.', '..', './', '../' } +function didLocationChange( + prev: ParsedLocation, + next: ParsedLocation, + deps: number, +) { + return !!( + (deps & BUILD_LOCATION_DEP_PATHNAME && prev.pathname !== next.pathname) || + (deps & BUILD_LOCATION_DEP_SEARCH && prev.search !== next.search) || + (deps & BUILD_LOCATION_DEP_HASH && prev.hash !== next.hash) || + (deps & BUILD_LOCATION_DEP_STATE && prev.state !== next.state) + ) +} + +function getBuildLocationDeps(next: ParsedLocation) { + return ((next as any).__TSR_buildLocationDeps ?? + BUILD_LOCATION_DEP_ALL) as number +} + +function getActiveLocationDeps( + activeOptions: LinkOptions['activeOptions'], + nextLocation: Pick, + externalLink: boolean, +): ActiveLocationDeps { + if (externalLink) { + return NO_ACTIVE_LOCATION_DEPS + } + + const exact = activeOptions?.exact ?? false + const includeSearch = activeOptions?.includeSearch ?? true + const includeHash = !!activeOptions?.includeHash + const ignoreUndefined = !activeOptions?.explicitUndefined + const nextSearchIsEmpty = isSearchEmpty(nextLocation.search, ignoreUndefined) + + return { + deps: + BUILD_LOCATION_DEP_PATHNAME | (includeHash ? BUILD_LOCATION_DEP_HASH : 0), + ignoreUndefined, + searchMode: !includeSearch + ? ACTIVE_LOCATION_SEARCH_NONE + : nextSearchIsEmpty + ? exact + ? ACTIVE_LOCATION_SEARCH_HAS_ENTRIES + : ACTIVE_LOCATION_SEARCH_NONE + : ACTIVE_LOCATION_SEARCH_FULL, + } +} + +function didActiveLocationChange( + prev: ParsedLocation, + next: ParsedLocation, + deps: ActiveLocationDeps, +) { + if ( + deps.deps & BUILD_LOCATION_DEP_PATHNAME && + prev.pathname !== next.pathname + ) { + return true + } + + if (deps.searchMode === ACTIVE_LOCATION_SEARCH_FULL) { + if (prev.search !== next.search) { + return true + } + } else if (deps.searchMode === ACTIVE_LOCATION_SEARCH_HAS_ENTRIES) { + if ( + hasSearchEntries(prev.search, deps.ignoreUndefined) !== + hasSearchEntries(next.search, deps.ignoreUndefined) + ) { + return true + } + } + + return !!(deps.deps & BUILD_LOCATION_DEP_HASH && prev.hash !== next.hash) +} + +function isSearchEmpty(search: unknown, ignoreUndefined: boolean): boolean { + return !hasSearchEntries(search, ignoreUndefined) +} + +function hasSearchEntries(search: unknown, ignoreUndefined: boolean): boolean { + if (!search || typeof search !== 'object') { + return false + } + + for (const key in search as Record) { + if ( + !ignoreUndefined || + (search as Record)[key] !== undefined + ) { + return true + } + } + + return false +} + type UseLinkReactProps = TComp extends keyof React.JSX.IntrinsicElements ? React.JSX.IntrinsicElements[TComp] : TComp extends React.ComponentType diff --git a/packages/react-router/tests/link.test.tsx b/packages/react-router/tests/link.test.tsx index 26cd07d988..3a2328a1ea 100644 --- a/packages/react-router/tests/link.test.tsx +++ b/packages/react-router/tests/link.test.tsx @@ -734,6 +734,103 @@ describe('Link', () => { expect(await screen.findByText('Posts 2')).toBeInTheDocument() }) + test('does not rebuild static next locations on unrelated search changes', async () => { + const history = createMemoryHistory({ initialEntries: ['/?page=0'] }) + + const rootRoute = createRootRoute({ + component: () => ( + + Static search + + ), + }) + + const router = createRouter({ + routeTree: rootRoute, + history, + }) + + const buildLocationSpy = vi.spyOn(router, 'buildLocation') + + render() + + const staticSearch = await screen.findByTestId('static-search') + + expect(staticSearch).toHaveClass('active') + + buildLocationSpy.mockClear() + + await act(async () => { + history.push('/?page=1') + }) + + await waitFor(() => { + expect(staticSearch).toHaveClass('inactive') + }) + + expect(buildLocationSpy).not.toHaveBeenCalled() + }) + + test('does not rerender when search changes do not affect next or active state', async () => { + const history = createMemoryHistory({ initialEntries: ['/?page=0'] }) + let renderCount = 0 + + function StaticSearchLink() { + renderCount++ + + return ( + + Static search + + ) + } + + const rootRoute = createRootRoute({ + component: () => , + }) + + const router = createRouter({ + routeTree: rootRoute, + history, + }) + + const buildLocationSpy = vi.spyOn(router, 'buildLocation') + + render() + + const staticSearch = await screen.findByTestId('static-search') + const initialRenderCount = renderCount + + expect(staticSearch).toHaveClass('active') + + buildLocationSpy.mockClear() + + await act(async () => { + history.push('/?page=1') + }) + + await waitFor(() => { + expect(router.state.location.search).toEqual({ page: 1 }) + }) + + expect(staticSearch).toHaveClass('active') + expect(renderCount).toBe(initialRenderCount) + expect(buildLocationSpy).not.toHaveBeenCalled() + }) + test('updates hash-sensitive active state immediately with and without hash=true', async () => { const rootRoute = createRootRoute({ component: () => ( diff --git a/packages/router-core/src/RouterProvider.ts b/packages/router-core/src/RouterProvider.ts index 52aeaffabb..c18708c930 100644 --- a/packages/router-core/src/RouterProvider.ts +++ b/packages/router-core/src/RouterProvider.ts @@ -42,6 +42,7 @@ export type BuildLocationFn = < opts: ToOptions & { leaveParams?: boolean _includeValidateSearch?: boolean + _collectLocationDeps?: boolean _isNavigate?: boolean }, ) => ParsedLocation diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 965fefda33..53db4eab3c 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -564,10 +564,17 @@ export interface BuildNextOptions { from?: string href?: string _fromLocation?: ParsedLocation + _collectLocationDeps?: boolean unsafeRelative?: 'path' _isNavigate?: boolean } +const BUILD_LOCATION_DEP_NONE = 0 +const BUILD_LOCATION_DEP_PATHNAME = 1 << 0 +const BUILD_LOCATION_DEP_SEARCH = 1 << 1 +const BUILD_LOCATION_DEP_HASH = 1 << 2 +const BUILD_LOCATION_DEP_STATE = 1 << 3 + type NavigationEventInfo = { fromLocation?: ParsedLocation toLocation: ParsedLocation @@ -1793,6 +1800,8 @@ export class RouterCore< * @link https://tanstack.com/router/latest/docs/framework/react/api/router/RouterType#buildlocation-method */ buildLocation: BuildLocationFn = (opts) => { + const collectLocationDeps = !!opts._collectLocationDeps + const build = ( dest: BuildNextOptions & { unmaskOnReload?: boolean @@ -1802,6 +1811,25 @@ export class RouterCore< const currentLocation = dest._fromLocation || this.pendingBuiltLocation || this.latestLocation + let locationDeps = BUILD_LOCATION_DEP_NONE + const toPath = dest.to == null ? undefined : `${dest.to}` + const toIsAbsolute = + !!toPath && toPath.charCodeAt(0) === 47 && toPath.charCodeAt(1) !== 47 + + if (collectLocationDeps) { + if (!dest.from && (!toPath || !toIsAbsolute)) { + locationDeps |= BUILD_LOCATION_DEP_PATHNAME + } + + if (dest.hash === true || typeof dest.hash === 'function') { + locationDeps |= BUILD_LOCATION_DEP_HASH + } + + if (dest.state === true || typeof dest.state === 'function') { + locationDeps |= BUILD_LOCATION_DEP_STATE + } + } + // Use lightweight matching - only computes what buildLocation needs // (fullPath, search, params) without creating full match objects const lightweightResult = this.matchRoutesLightweight(currentLocation) @@ -1852,6 +1880,15 @@ export class RouterCore< ? this.resolvePathWithBase(fromPath, `${dest.to}`) : this.resolvePathWithBase(fromPath, '.') + if ( + collectLocationDeps && + dest.params !== false && + dest.params !== null && + nextTo.includes('$') + ) { + locationDeps |= BUILD_LOCATION_DEP_PATHNAME + } + // Resolve the next params const nextParams = dest.params === false || dest.params === null @@ -1879,6 +1916,20 @@ export class RouterCore< destRoutes = [...destRoutes, this.options.notFoundRoute] } + if ( + collectLocationDeps && + (dest.search === true || + typeof dest.search === 'function' || + destRoutes.some((route) => + routeNeedsCurrentSearch( + route, + opts._includeValidateSearch ?? false, + ), + )) + ) { + locationDeps |= BUILD_LOCATION_DEP_SEARCH + } + // If there are any params, we need to stringify them if (Object.keys(nextParams).length > 0) { for (const route of destRoutes) { @@ -1999,7 +2050,7 @@ export class RouterCore< publicHref = href } - return { + const nextLocation = { publicHref, href, pathname: nextPathname, @@ -2010,6 +2061,12 @@ export class RouterCore< external, unmaskOnReload: dest.unmaskOnReload, } + + if (collectLocationDeps) { + setBuildLocationDeps(nextLocation, locationDeps) + } + + return nextLocation } const buildWithMatches = ( @@ -2057,6 +2114,13 @@ export class RouterCore< if (maskedNext) { next.maskedLocation = maskedNext + + if (collectLocationDeps) { + setBuildLocationDeps( + next, + getBuildLocationDeps(next) | getBuildLocationDeps(maskedNext), + ) + } } return next @@ -3058,6 +3122,27 @@ function applySearchMiddleware({ return middleware(search, dest, _includeValidateSearch ?? false) } +function routeNeedsCurrentSearch( + route: AnyRoute, + includeValidateSearch: boolean, +) { + return !!( + route.options.search?.middlewares?.length || + route.options.preSearchFilters?.length || + route.options.postSearchFilters?.length || + (includeValidateSearch && route.options.validateSearch) + ) +} + +function getBuildLocationDeps(location: ParsedLocation): number { + return ((location as any).__TSR_buildLocationDeps ?? + BUILD_LOCATION_DEP_NONE) as number +} + +function setBuildLocationDeps(location: ParsedLocation, deps: number) { + ;(location as any).__TSR_buildLocationDeps = deps +} + function buildMiddlewareChain(destRoutes: ReadonlyArray) { const context = { dest: null as unknown as BuildNextOptions, From a7390816b7d5021b175b3e1af8fde925707278a5 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 21 Mar 2026 00:02:15 +0100 Subject: [PATCH 2/5] perf: narrow React Link active search dependencies Track only the current search keys and key-count information that active-state matching actually needs, so static search links can skip rerenders even with includeSearch enabled. Simplify buildLocation dependency collection and extend the React client-nav benchmark to measure both includeSearch modes. --- benchmarks/client-nav/react/app.tsx | 40 +++++-- benchmarks/client-nav/react/setup.ts | 2 +- benchmarks/client-nav/react/speed.bench.ts | 6 +- link-performance-investigation.md | 48 +++++---- packages/react-router/src/link.tsx | 111 +++++++++++--------- packages/react-router/tests/link.test.tsx | 115 +++++++++++++++++++++ packages/router-core/src/RouterProvider.ts | 2 +- packages/router-core/src/router.ts | 53 +++++----- 8 files changed, 268 insertions(+), 109 deletions(-) diff --git a/benchmarks/client-nav/react/app.tsx b/benchmarks/client-nav/react/app.tsx index 82d23f0727..9d2d5f0c1c 100644 --- a/benchmarks/client-nav/react/app.tsx +++ b/benchmarks/client-nav/react/app.tsx @@ -11,7 +11,10 @@ import { } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' -export type Scenario = 'default' | 'static-search-links' +export type Scenario = + | 'default' + | 'static-search-links' + | 'static-search-links-active-search' function runPerfSelectorComputation(seed: number) { let value = Math.trunc(seed) | 0 @@ -52,12 +55,19 @@ function Links() { ) } -function StaticSearchLinks(props: { linkId: number }) { +function StaticSearchLinks(props: { + linkId: number + includeActiveSearch: boolean +}) { + const activeOptions = props.includeActiveSearch + ? undefined + : { includeSearch: false as const } + return ( Link @@ -81,11 +91,15 @@ function Root() { ) } -function StaticSearchLinksRoot() { +function StaticSearchLinksRoot(props: { includeActiveSearch: boolean }) { return ( <> {staticSearchLinkIds.map((linkId) => ( - + ))} @@ -96,19 +110,29 @@ export function mountTestApp( container: Element, scenario: Scenario = 'default', ) { + const isStaticSearchScenario = scenario !== 'default' + const rootRoute = createRootRoute({ - component: scenario === 'default' ? Root : StaticSearchLinksRoot, + component: isStaticSearchScenario + ? () => ( + + ) + : Root, }) const route = createRoute({ getParentRoute: () => rootRoute, - path: scenario === 'default' ? '/$id' : '/links', + path: isStaticSearchScenario ? '/links' : '/$id', component: () =>
, }) const router = createRouter({ history: createMemoryHistory({ - initialEntries: [scenario === 'default' ? '/0' : '/links'], + initialEntries: [isStaticSearchScenario ? '/links' : '/0'], }), scrollRestoration: true, routeTree: rootRoute.addChildren([route]), diff --git a/benchmarks/client-nav/react/setup.ts b/benchmarks/client-nav/react/setup.ts index 2ca0c1b37a..cf26d34fd8 100644 --- a/benchmarks/client-nav/react/setup.ts +++ b/benchmarks/client-nav/react/setup.ts @@ -50,7 +50,7 @@ export function setup(scenario: Scenario = 'default') { : () => navigate({ to: '/links', - search: { id: id++ }, + search: { id: id++, stable: '1' }, replace: true, }) await router.load() diff --git a/benchmarks/client-nav/react/speed.bench.ts b/benchmarks/client-nav/react/speed.bench.ts index 6c594b1f2f..79c3d2e3ef 100644 --- a/benchmarks/client-nav/react/speed.bench.ts +++ b/benchmarks/client-nav/react/speed.bench.ts @@ -36,7 +36,11 @@ function registerBenchmark(name: string, test: ReturnType) { describe('client-nav', () => { registerBenchmark('client-side navigation loop (react)', setup()) registerBenchmark( - 'client-side navigation loop with static search links (react)', + 'client-side navigation loop with static search links and includeSearch=false (react)', setup('static-search-links'), ) + registerBenchmark( + 'client-side navigation loop with static search links and includeSearch=true (react)', + setup('static-search-links-active-search'), + ) }) diff --git a/link-performance-investigation.md b/link-performance-investigation.md index 5425ea2f5c..e448986476 100644 --- a/link-performance-investigation.md +++ b/link-performance-investigation.md @@ -188,9 +188,9 @@ This isolates the intended search-only invalidation case. Current implementation vs `main`: -- `main`: `37.94 hz`, mean `26.36 ms` -- current: `37.12 hz`, mean `26.94 ms` -- Result: roughly flat to slightly worse (`-2.2%` throughput) +- `main`: `38.78 hz`, mean `25.79 ms` +- current: `36.33 hz`, mean `27.53 ms` +- Result: still slightly worse in the broad benchmark (`-6.3%` throughput in the latest run) Interpretation: @@ -201,9 +201,9 @@ Interpretation: Current implementation vs `main`: -- `main`: `15.93 hz`, mean `62.76 ms` -- current: `26.33 hz`, mean `37.98 ms` -- Result: `+65.2%` throughput, `-39.5%` mean time +- `main`: `16.42 hz`, mean `60.92 ms` +- current: `27.03 hz`, mean `37.00 ms` +- Result: `+64.7%` throughput, `-39.3%` mean time Interpretation: @@ -212,30 +212,39 @@ Interpretation: ### Search-only benchmark, default `includeSearch: true` -Measured by temporarily removing `activeOptions={{ includeSearch: false }}` from the new benchmark. +Follow-up work narrowed active-search dependency tracking for static-search links so React no longer subscribes to the full current search object in the common partial-match case. + +The active-state dependency now distinguishes: + +- no current-search dependency +- selected current-search keys only +- selected current-search keys plus exact current-search entry count + +That means common links such as `search={{ page: 0 }}` with default `includeSearch: true` only react to current `page`, not unrelated current search keys. Current implementation vs `main`: -- `main`: `17.36 hz`, mean `57.60 ms` -- current: `18.36 hz`, mean `54.47 ms` -- Result: `+5.8%` throughput, `-5.4%` mean time +- `main`: `14.46 hz`, mean `69.16 ms` +- current: `20.28 hz`, mean `49.31 ms` +- Result: `+40.2%` throughput, `-28.7%` mean time Interpretation: -- The gain is still real, but much smaller. -- Default `includeSearch: true` means React `Link` usually still rerenders to recompute `isActive` when current search changes. -- The remaining win comes from reusing cached `next` and skipping `buildLocation`. +- The default `includeSearch: true` case now benefits much more because React can skip rerenders when unrelated current search keys change. +- React still rerenders when the selected search keys or exact-search key count can affect `isActive`. +- The remaining work is now much closer to the true semantic dependency of active-state matching. ### Bundle size Current implementation vs `main`: -- `react-router.minimal`: `90682 -> 91453 gzip` (`+771 B`, `+0.85%`) -- `react-router.full`: `93928 -> 94692 gzip` (`+764 B`, `+0.81%`) +- `react-router.minimal`: `90682 -> 91531 gzip` (`+849 B`, `+0.94%`) +- `react-router.full`: `93928 -> 94779 gzip` (`+851 B`, `+0.91%`) Interpretation: - The core-assisted React-only approach is still larger than `main`, but much better than the original three-adapter duplicated approach. +- Replacing the hidden dependency metadata property with an internal `_locationDeps` target simplified the implementation, but it did not materially reduce the emitted React bundle on its own. ## What Worked @@ -253,16 +262,15 @@ Interpretation: ## Current Understanding - The optimization target is real. -- The common-case default `includeSearch: true` still benefits, but only modestly, because React usually still has to rerender for active-state changes. +- The common-case default `includeSearch: true` can benefit substantially when a static-search link only depends on a small subset of current search keys. - The biggest win appears when search changes affect neither `next` nor `isActive`. - The current mixed benchmark suggests there is still a larger amount of unavoidable pathname-driven work in the general case. ## Open Questions / Next Steps -1. Can active-state search dependency become narrower for common static-search links, even when `includeSearch` stays at its default `true`? -2. Can the dependency mask be compressed or inferred with less emitted code to reduce the remaining React bundle increase? -3. Is there a cheap way to distinguish "needs exact current search" from "only needs to know whether current search exists" in more common cases? -4. Should the same core-assisted pattern eventually be extended to Solid and Vue, or is React the only adapter worth optimizing at this level? +1. Can the remaining React/client-nav regression be explained by unavoidable pathname work, or is there still avoidable `Link` overhead in the mixed benchmark? +2. Can the dependency metadata be compressed further without giving up the selected-key / key-count active-search win? +3. Should the same core-assisted pattern eventually be extended to Solid and Vue, or is React the only adapter worth optimizing at this level? ## Practical Status diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index 6b61fa8ad6..dd50aec772 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -448,8 +448,10 @@ export function useLinkProps< return previousBuildLocation } + const locationDeps = { value: BUILD_LOCATION_DEP_ALL } + const next = router.buildLocation({ - _collectLocationDeps: true, + _locationDeps: locationDeps, _fromLocation: currentLocation, ..._options, } as any) @@ -460,7 +462,7 @@ export function useLinkProps< next, deps: _options._fromLocation ? BUILD_LOCATION_DEP_NONE - : getBuildLocationDeps(next), + : locationDeps.value, options: _options, } }, [router, currentLocation, _options]) @@ -815,29 +817,28 @@ type BuildLocationState = { type ActiveLocationDeps = { deps: number + expectedSearchCount: number ignoreUndefined: boolean - searchMode: number + searchKeys?: ReadonlyArray } const BUILD_LOCATION_DEP_NONE = 0 -const BUILD_LOCATION_DEP_PATHNAME = 1 << 0 -const BUILD_LOCATION_DEP_SEARCH = 1 << 1 -const BUILD_LOCATION_DEP_HASH = 1 << 2 -const BUILD_LOCATION_DEP_STATE = 1 << 3 -const BUILD_LOCATION_DEP_ALL = - BUILD_LOCATION_DEP_PATHNAME | - BUILD_LOCATION_DEP_SEARCH | - BUILD_LOCATION_DEP_HASH | - BUILD_LOCATION_DEP_STATE +const BUILD_LOCATION_DEP_PATHNAME = 1 +const BUILD_LOCATION_DEP_SEARCH = 2 +const BUILD_LOCATION_DEP_HASH = 4 +const BUILD_LOCATION_DEP_STATE = 8 +const BUILD_LOCATION_DEP_ALL = 15 -const ACTIVE_LOCATION_SEARCH_NONE = 0 -const ACTIVE_LOCATION_SEARCH_FULL = 1 -const ACTIVE_LOCATION_SEARCH_HAS_ENTRIES = 2 +const ACTIVE_LOCATION_SEARCH_COUNT_NONE = -1 + +const SEARCH_EXPLICIT_UNDEFINED_OPTIONS = { + ignoreUndefined: false, +} as const const NO_ACTIVE_LOCATION_DEPS: ActiveLocationDeps = { deps: BUILD_LOCATION_DEP_NONE, + expectedSearchCount: ACTIVE_LOCATION_SEARCH_COUNT_NONE, ignoreUndefined: true, - searchMode: ACTIVE_LOCATION_SEARCH_NONE, } const composeHandlers = @@ -887,11 +888,6 @@ function didLocationChange( ) } -function getBuildLocationDeps(next: ParsedLocation) { - return ((next as any).__TSR_buildLocationDeps ?? - BUILD_LOCATION_DEP_ALL) as number -} - function getActiveLocationDeps( activeOptions: LinkOptions['activeOptions'], nextLocation: Pick, @@ -905,19 +901,19 @@ function getActiveLocationDeps( const includeSearch = activeOptions?.includeSearch ?? true const includeHash = !!activeOptions?.includeHash const ignoreUndefined = !activeOptions?.explicitUndefined - const nextSearchIsEmpty = isSearchEmpty(nextLocation.search, ignoreUndefined) + const searchKeys = includeSearch + ? getSearchKeys(nextLocation.search, ignoreUndefined) + : undefined return { deps: BUILD_LOCATION_DEP_PATHNAME | (includeHash ? BUILD_LOCATION_DEP_HASH : 0), + expectedSearchCount: + includeSearch && exact + ? (searchKeys?.length ?? BUILD_LOCATION_DEP_NONE) + : ACTIVE_LOCATION_SEARCH_COUNT_NONE, ignoreUndefined, - searchMode: !includeSearch - ? ACTIVE_LOCATION_SEARCH_NONE - : nextSearchIsEmpty - ? exact - ? ACTIVE_LOCATION_SEARCH_HAS_ENTRIES - : ACTIVE_LOCATION_SEARCH_NONE - : ACTIVE_LOCATION_SEARCH_FULL, + searchKeys: searchKeys?.length ? searchKeys : undefined, } } @@ -933,14 +929,24 @@ function didActiveLocationChange( return true } - if (deps.searchMode === ACTIVE_LOCATION_SEARCH_FULL) { - if (prev.search !== next.search) { - return true + if (deps.searchKeys?.length) { + const prevSearch = prev.search as Record + const nextSearch = next.search as Record + const deepEqualOptions = deps.ignoreUndefined + ? undefined + : SEARCH_EXPLICIT_UNDEFINED_OPTIONS + + for (const key of deps.searchKeys) { + if (!deepEqual(prevSearch?.[key], nextSearch?.[key], deepEqualOptions)) { + return true + } } - } else if (deps.searchMode === ACTIVE_LOCATION_SEARCH_HAS_ENTRIES) { + } + + if (deps.expectedSearchCount !== ACTIVE_LOCATION_SEARCH_COUNT_NONE) { if ( - hasSearchEntries(prev.search, deps.ignoreUndefined) !== - hasSearchEntries(next.search, deps.ignoreUndefined) + getSearchEntryCount(prev.search, deps.ignoreUndefined) !== + getSearchEntryCount(next.search, deps.ignoreUndefined) ) { return true } @@ -949,25 +955,32 @@ function didActiveLocationChange( return !!(deps.deps & BUILD_LOCATION_DEP_HASH && prev.hash !== next.hash) } -function isSearchEmpty(search: unknown, ignoreUndefined: boolean): boolean { - return !hasSearchEntries(search, ignoreUndefined) -} +function getSearchKeys(search: unknown, ignoreUndefined: boolean) { + const searchRecord = search as Record -function hasSearchEntries(search: unknown, ignoreUndefined: boolean): boolean { - if (!search || typeof search !== 'object') { - return false - } + const keys = [] as Array - for (const key in search as Record) { - if ( - !ignoreUndefined || - (search as Record)[key] !== undefined - ) { - return true + for (const key in searchRecord) { + if (!ignoreUndefined || searchRecord[key] !== undefined) { + keys.push(key) } } - return false + return keys +} + +function getSearchEntryCount(search: unknown, ignoreUndefined: boolean) { + const searchRecord = search as Record + + let count = BUILD_LOCATION_DEP_NONE + + for (const key in searchRecord) { + if (!ignoreUndefined || searchRecord[key] !== undefined) { + count++ + } + } + + return count } type UseLinkReactProps = TComp extends keyof React.JSX.IntrinsicElements diff --git a/packages/react-router/tests/link.test.tsx b/packages/react-router/tests/link.test.tsx index 3a2328a1ea..32e098774f 100644 --- a/packages/react-router/tests/link.test.tsx +++ b/packages/react-router/tests/link.test.tsx @@ -831,6 +831,121 @@ describe('Link', () => { expect(buildLocationSpy).not.toHaveBeenCalled() }) + test('does not rerender when unrelated search keys change for partial active search', async () => { + const history = createMemoryHistory({ + initialEntries: ['/?page=0&filter=first'], + }) + let renderCount = 0 + + function StaticSearchLink() { + renderCount++ + + return ( + + Static search + + ) + } + + const rootRoute = createRootRoute({ + component: () => , + }) + + const router = createRouter({ + routeTree: rootRoute, + history, + }) + + const buildLocationSpy = vi.spyOn(router, 'buildLocation') + + render() + + const staticSearch = await screen.findByTestId('static-search') + const initialRenderCount = renderCount + + expect(staticSearch).toHaveClass('active') + + buildLocationSpy.mockClear() + + await act(async () => { + history.push('/?page=0&filter=second') + }) + + await waitFor(() => { + expect(router.state.location.search).toEqual({ + filter: 'second', + page: 0, + }) + }) + + expect(staticSearch).toHaveClass('active') + expect(renderCount).toBe(initialRenderCount) + expect(buildLocationSpy).not.toHaveBeenCalled() + }) + + test('does not rerender when exact active search keeps the same key count', async () => { + const history = createMemoryHistory({ + initialEntries: ['/?page=0&filter=first'], + }) + let renderCount = 0 + + function StaticSearchLink() { + renderCount++ + + return ( + + Static search + + ) + } + + const rootRoute = createRootRoute({ + component: () => , + }) + + const router = createRouter({ + routeTree: rootRoute, + history, + }) + + const buildLocationSpy = vi.spyOn(router, 'buildLocation') + + render() + + const staticSearch = await screen.findByTestId('static-search') + const initialRenderCount = renderCount + + expect(staticSearch).toHaveClass('inactive') + + buildLocationSpy.mockClear() + + await act(async () => { + history.push('/?page=0&filter=second') + }) + + await waitFor(() => { + expect(router.state.location.search).toEqual({ + filter: 'second', + page: 0, + }) + }) + + expect(staticSearch).toHaveClass('inactive') + expect(renderCount).toBe(initialRenderCount) + expect(buildLocationSpy).not.toHaveBeenCalled() + }) + test('updates hash-sensitive active state immediately with and without hash=true', async () => { const rootRoute = createRootRoute({ component: () => ( diff --git a/packages/router-core/src/RouterProvider.ts b/packages/router-core/src/RouterProvider.ts index c18708c930..2f6723c880 100644 --- a/packages/router-core/src/RouterProvider.ts +++ b/packages/router-core/src/RouterProvider.ts @@ -42,7 +42,7 @@ export type BuildLocationFn = < opts: ToOptions & { leaveParams?: boolean _includeValidateSearch?: boolean - _collectLocationDeps?: boolean + _locationDeps?: { value: number } _isNavigate?: boolean }, ) => ParsedLocation diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 53db4eab3c..af464f760b 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -564,16 +564,16 @@ export interface BuildNextOptions { from?: string href?: string _fromLocation?: ParsedLocation - _collectLocationDeps?: boolean + _locationDeps?: { value: number } unsafeRelative?: 'path' _isNavigate?: boolean } const BUILD_LOCATION_DEP_NONE = 0 -const BUILD_LOCATION_DEP_PATHNAME = 1 << 0 -const BUILD_LOCATION_DEP_SEARCH = 1 << 1 -const BUILD_LOCATION_DEP_HASH = 1 << 2 -const BUILD_LOCATION_DEP_STATE = 1 << 3 +const BUILD_LOCATION_DEP_PATHNAME = 1 +const BUILD_LOCATION_DEP_SEARCH = 2 +const BUILD_LOCATION_DEP_HASH = 4 +const BUILD_LOCATION_DEP_STATE = 8 type NavigationEventInfo = { fromLocation?: ParsedLocation @@ -1800,7 +1800,8 @@ export class RouterCore< * @link https://tanstack.com/router/latest/docs/framework/react/api/router/RouterType#buildlocation-method */ buildLocation: BuildLocationFn = (opts) => { - const collectLocationDeps = !!opts._collectLocationDeps + const locationDepsTarget = opts._locationDeps + let collectedLocationDeps = BUILD_LOCATION_DEP_NONE const build = ( dest: BuildNextOptions & { @@ -1816,7 +1817,7 @@ export class RouterCore< const toIsAbsolute = !!toPath && toPath.charCodeAt(0) === 47 && toPath.charCodeAt(1) !== 47 - if (collectLocationDeps) { + if (locationDepsTarget) { if (!dest.from && (!toPath || !toIsAbsolute)) { locationDeps |= BUILD_LOCATION_DEP_PATHNAME } @@ -1881,7 +1882,7 @@ export class RouterCore< : this.resolvePathWithBase(fromPath, '.') if ( - collectLocationDeps && + locationDepsTarget && dest.params !== false && dest.params !== null && nextTo.includes('$') @@ -1917,7 +1918,7 @@ export class RouterCore< } if ( - collectLocationDeps && + locationDepsTarget && (dest.search === true || typeof dest.search === 'function' || destRoutes.some((route) => @@ -2062,8 +2063,8 @@ export class RouterCore< unmaskOnReload: dest.unmaskOnReload, } - if (collectLocationDeps) { - setBuildLocationDeps(nextLocation, locationDeps) + if (locationDepsTarget) { + collectedLocationDeps |= locationDeps } return nextLocation @@ -2114,26 +2115,29 @@ export class RouterCore< if (maskedNext) { next.maskedLocation = maskedNext - - if (collectLocationDeps) { - setBuildLocationDeps( - next, - getBuildLocationDeps(next) | getBuildLocationDeps(maskedNext), - ) - } } return next } if (opts.mask) { - return buildWithMatches(opts, { + const next = buildWithMatches(opts, { from: opts.from, ...opts.mask, }) + if (locationDepsTarget) { + locationDepsTarget.value = collectedLocationDeps + } + return next } - return buildWithMatches(opts) + const next = buildWithMatches(opts) + + if (locationDepsTarget) { + locationDepsTarget.value = collectedLocationDeps + } + + return next } commitLocationPromise: undefined | ControlledPromise @@ -3134,15 +3138,6 @@ function routeNeedsCurrentSearch( ) } -function getBuildLocationDeps(location: ParsedLocation): number { - return ((location as any).__TSR_buildLocationDeps ?? - BUILD_LOCATION_DEP_NONE) as number -} - -function setBuildLocationDeps(location: ParsedLocation, deps: number) { - ;(location as any).__TSR_buildLocationDeps = deps -} - function buildMiddlewareChain(destRoutes: ReadonlyArray) { const context = { dest: null as unknown as BuildNextOptions, From 73758e0dbbbb58cbca4f4e8567d2c64d7a2e0ef3 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 21 Mar 2026 08:05:40 +0100 Subject: [PATCH 3/5] shaving size --- packages/react-router/src/link.tsx | 54 +++++++----------------------- 1 file changed, 13 insertions(+), 41 deletions(-) diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index dd50aec772..a54973731d 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -408,18 +408,14 @@ export function useLinkProps< (prev: ParsedLocation, next: ParsedLocation) => { const buildLocation = buildLocationRef.current - if ( - didLocationChange( + return ( + !didLocationChange( prev, next, buildLocation?.deps ?? BUILD_LOCATION_DEP_ALL, - ) || - didActiveLocationChange(prev, next, activeLocationDepsRef.current) - ) { - return false - } - - return true + ) && + !didActiveLocationChange(prev, next, activeLocationDepsRef.current) + ) }, [], ) @@ -436,9 +432,7 @@ export function useLinkProps< const previousBuildLocation = buildLocationRef.current if ( - previousBuildLocation && - previousBuildLocation.router === router && - previousBuildLocation.options === _options && + previousBuildLocation?.options === _options && !didLocationChange( previousBuildLocation.location, currentLocation, @@ -457,7 +451,6 @@ export function useLinkProps< } as any) return { - router, location: currentLocation, next, deps: _options._fromLocation @@ -527,11 +520,7 @@ export function useLinkProps< () => getActiveLocationDeps( activeOptions, - { - hash: next.hash, - pathname: next.pathname, - search: next.search, - }, + next, !!externalLink, ), [activeOptions, externalLink, next.hash, next.pathname, next.search], @@ -808,7 +797,6 @@ const intersectionObserverOptions: IntersectionObserverInit = { } type BuildLocationState = { - router: AnyRouter location: ParsedLocation next: ParsedLocation deps: number @@ -910,7 +898,7 @@ function getActiveLocationDeps( BUILD_LOCATION_DEP_PATHNAME | (includeHash ? BUILD_LOCATION_DEP_HASH : 0), expectedSearchCount: includeSearch && exact - ? (searchKeys?.length ?? BUILD_LOCATION_DEP_NONE) + ? (searchKeys?.length ?? 0) : ACTIVE_LOCATION_SEARCH_COUNT_NONE, ignoreUndefined, searchKeys: searchKeys?.length ? searchKeys : undefined, @@ -945,8 +933,8 @@ function didActiveLocationChange( if (deps.expectedSearchCount !== ACTIVE_LOCATION_SEARCH_COUNT_NONE) { if ( - getSearchEntryCount(prev.search, deps.ignoreUndefined) !== - getSearchEntryCount(next.search, deps.ignoreUndefined) + getSearchKeys(prev.search, deps.ignoreUndefined).length !== + getSearchKeys(next.search, deps.ignoreUndefined).length ) { return true } @@ -955,13 +943,11 @@ function didActiveLocationChange( return !!(deps.deps & BUILD_LOCATION_DEP_HASH && prev.hash !== next.hash) } -function getSearchKeys(search: unknown, ignoreUndefined: boolean) { - const searchRecord = search as Record - +function getSearchKeys(search: Record, ignoreUndefined: boolean) { const keys = [] as Array - for (const key in searchRecord) { - if (!ignoreUndefined || searchRecord[key] !== undefined) { + for (const key in search) { + if (!ignoreUndefined || search[key] !== undefined) { keys.push(key) } } @@ -969,20 +955,6 @@ function getSearchKeys(search: unknown, ignoreUndefined: boolean) { return keys } -function getSearchEntryCount(search: unknown, ignoreUndefined: boolean) { - const searchRecord = search as Record - - let count = BUILD_LOCATION_DEP_NONE - - for (const key in searchRecord) { - if (!ignoreUndefined || searchRecord[key] !== undefined) { - count++ - } - } - - return count -} - type UseLinkReactProps = TComp extends keyof React.JSX.IntrinsicElements ? React.JSX.IntrinsicElements[TComp] : TComp extends React.ComponentType From 4751ea8cbbae260ab1ac02c559dbb886edbfd4be Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 21 Mar 2026 08:35:47 +0100 Subject: [PATCH 4/5] remove search validation from buildLocation --- packages/react-router/src/link.tsx | 2 ++ packages/router-core/src/router.ts | 32 ++++-------------------------- 2 files changed, 6 insertions(+), 28 deletions(-) diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index a54973731d..040913d190 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -523,6 +523,8 @@ export function useLinkProps< next, !!externalLink, ), + // TODO: do we need full `next` here? or could we re-compute this only when next.search changes? + // eslint-disable-next-line react-hooks/exhaustive-deps -- next is tracked as its properties [activeOptions, externalLink, next.hash, next.pathname, next.search], ) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index af464f760b..483fbfe0c1 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1689,7 +1689,6 @@ export class RouterCore< private matchRoutesLightweight(location: ParsedLocation): { matchedRoutes: ReadonlyArray fullPath: string - search: Record params: Record } { const { matchedRoutes, routeParams, parsedParams } = this.getMatchedRoutes( @@ -1697,28 +1696,6 @@ export class RouterCore< ) const lastRoute = last(matchedRoutes)! - // I don't know if we should run the full search middleware chain, or just validateSearch - // // Accumulate search validation through the route chain - // const accumulatedSearch: Record = applySearchMiddleware({ - // search: { ...location.search }, - // dest: location, - // destRoutes: matchedRoutes, - // _includeValidateSearch: true, - // }) - - // Accumulate search validation through route chain - const accumulatedSearch = { ...location.search } - for (const route of matchedRoutes) { - try { - Object.assign( - accumulatedSearch, - validateSearch(route.options.validateSearch, accumulatedSearch), - ) - } catch { - // Ignore errors, we're not actually routing - } - } - // Determine params: reuse from state if possible, otherwise parse const lastStateMatchId = last(this.stores.matchesId.state) const lastStateMatch = @@ -1756,7 +1733,6 @@ export class RouterCore< return { matchedRoutes, fullPath: lastRoute.fullPath, - search: accumulatedSearch, params, } } @@ -1813,11 +1789,11 @@ export class RouterCore< dest._fromLocation || this.pendingBuiltLocation || this.latestLocation let locationDeps = BUILD_LOCATION_DEP_NONE - const toPath = dest.to == null ? undefined : `${dest.to}` - const toIsAbsolute = - !!toPath && toPath.charCodeAt(0) === 47 && toPath.charCodeAt(1) !== 47 if (locationDepsTarget) { + const toPath = dest.to == null ? undefined : `${dest.to}` + const toIsAbsolute = + !!toPath && toPath.charCodeAt(0) === 47 && toPath.charCodeAt(1) !== 47 if (!dest.from && (!toPath || !toIsAbsolute)) { locationDeps |= BUILD_LOCATION_DEP_PATHNAME } @@ -1868,7 +1844,7 @@ export class RouterCore< const fromPath = this.resolvePathWithBase(defaultedFromPath, '.') // From search should always use the current location - const fromSearch = lightweightResult.search + const fromSearch = currentLocation.search // Same with params. It can't hurt to provide as many as possible const fromParams = Object.assign( Object.create(null), From 8b1ce038dddfd7266b3f41b076348968f51997d3 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sun, 22 Mar 2026 18:06:27 +0100 Subject: [PATCH 5/5] i dont think this is good, just technically fun --- benchmarks/client-nav/react/app.tsx | 44 +++++- benchmarks/client-nav/react/setup.ts | 3 +- benchmarks/client-nav/react/speed.bench.ts | 68 ++++---- packages/react-router/src/link.tsx | 171 +++++---------------- packages/router-core/src/router.ts | 8 +- 5 files changed, 120 insertions(+), 174 deletions(-) diff --git a/benchmarks/client-nav/react/app.tsx b/benchmarks/client-nav/react/app.tsx index cad766e26c..5889ce0c46 100644 --- a/benchmarks/client-nav/react/app.tsx +++ b/benchmarks/client-nav/react/app.tsx @@ -34,6 +34,7 @@ const noop = () => {} const rootSelectors = Array.from({ length: 10 }, (_, index) => index) const routeSelectors = Array.from({ length: 6 }, (_, index) => index) const linkGroups = Array.from({ length: 4 }, (_, index) => index) +const staticContextLinkIds = Array.from({ length: 8 }, (_, index) => index) function RootParamsSubscriber() { const params = useParams({ @@ -99,7 +100,10 @@ function LinkPanel() { data-testid={groupIndex === 0 ? 'go-ctx' : undefined} to="/ctx/$id" params={{ id: ctxId }} - search={true} + search={(prev: Record) => ({ + ...prev, + noise: '0', + })} replace activeOptions={{ includeSearch: false }} > @@ -128,6 +132,43 @@ function LinkPanel() { ) } +function StaticContextLinkPanel() { + return ( + <> + {staticContextLinkIds.map((linkId) => ( +
+ + {`Context search ${linkId}`} + + + {`Context search ignore ${linkId}`} + + + {`Context search exact ${linkId}`} + +
+ ))} + + ) +} + function Root() { return ( <> @@ -138,6 +179,7 @@ function Root() { ))} + ) diff --git a/benchmarks/client-nav/react/setup.ts b/benchmarks/client-nav/react/setup.ts index c637baf570..a18daffb43 100644 --- a/benchmarks/client-nav/react/setup.ts +++ b/benchmarks/client-nav/react/setup.ts @@ -79,7 +79,8 @@ export function setup() { () => navigate({ to: '/ctx/$id', - params: { id: 2 }, + params: { id: 1 }, + search: { page: 1, filter: 'all', noise: '1' }, replace: true, }), () => click('go-items-2', cachedLinks), diff --git a/benchmarks/client-nav/react/speed.bench.ts b/benchmarks/client-nav/react/speed.bench.ts index 79c3d2e3ef..fcc15b5fbc 100644 --- a/benchmarks/client-nav/react/speed.bench.ts +++ b/benchmarks/client-nav/react/speed.bench.ts @@ -1,46 +1,34 @@ import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' -function registerBenchmark(name: string, test: ReturnType) { - describe(name, () => { - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( - name, - async () => { - for (let i = 0; i < 10; i++) { - await test.tick() - } - }, - { - warmupIterations: 100, - time: 10_000, - setup: test.before, - teardown: test.after, - }, - ) - }) -} - describe('client-nav', () => { - registerBenchmark('client-side navigation loop (react)', setup()) - registerBenchmark( - 'client-side navigation loop with static search links and includeSearch=false (react)', - setup('static-search-links'), - ) - registerBenchmark( - 'client-side navigation loop with static search links and includeSearch=true (react)', - setup('static-search-links-active-search'), + const test = setup() + + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( + 'client-side navigation loop (react)', + async () => { + for (let i = 0; i < 10; i++) { + await test.tick() + } + }, + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, ) }) diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index 040913d190..558a880e11 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -398,33 +398,18 @@ export function useLinkProps< // eslint-disable-next-line react-hooks/rules-of-hooks const buildLocationRef = React.useRef(null) - // eslint-disable-next-line react-hooks/rules-of-hooks - const activeLocationDepsRef = React.useRef( - NO_ACTIVE_LOCATION_DEPS, - ) // eslint-disable-next-line react-hooks/rules-of-hooks - const locationStateEqual = React.useCallback( - (prev: ParsedLocation, next: ParsedLocation) => { - const buildLocation = buildLocationRef.current - - return ( - !didLocationChange( - prev, - next, - buildLocation?.deps ?? BUILD_LOCATION_DEP_ALL, - ) && - !didActiveLocationChange(prev, next, activeLocationDepsRef.current) - ) - }, - [], + const shouldReuseBuildLocation = React.useMemo( + () => canReuseBuildLocation(_options), + [_options], ) // eslint-disable-next-line react-hooks/rules-of-hooks const currentLocation = useStore( router.stores.location, (l) => l, - locationStateEqual, + (prev, next) => prev.href === next.href, ) // eslint-disable-next-line react-hooks/rules-of-hooks @@ -432,6 +417,7 @@ export function useLinkProps< const previousBuildLocation = buildLocationRef.current if ( + shouldReuseBuildLocation && previousBuildLocation?.options === _options && !didLocationChange( previousBuildLocation.location, @@ -442,23 +428,34 @@ export function useLinkProps< return previousBuildLocation } - const locationDeps = { value: BUILD_LOCATION_DEP_ALL } + const shouldCollectLocationDeps = + shouldReuseBuildLocation && + !( + (previousBuildLocation?.deps ?? BUILD_LOCATION_DEP_NONE) & + (BUILD_LOCATION_DEP_PATHNAME | BUILD_LOCATION_DEP_SEARCH) + ) + + const locationDeps = shouldCollectLocationDeps + ? { value: BUILD_LOCATION_DEP_ALL } + : undefined const next = router.buildLocation({ - _locationDeps: locationDeps, + ...(locationDeps ? { _locationDeps: locationDeps } : null), _fromLocation: currentLocation, ..._options, } as any) - return { + const result = { location: currentLocation, next, deps: _options._fromLocation ? BUILD_LOCATION_DEP_NONE - : locationDeps.value, + : (locationDeps?.value ?? BUILD_LOCATION_DEP_ALL), options: _options, } - }, [router, currentLocation, _options]) + buildLocationRef.current = result + return result + }, [router, currentLocation, _options, shouldReuseBuildLocation]) const next = buildLocation.next @@ -515,25 +512,6 @@ export function useLinkProps< return undefined }, [to, hrefOption, router.protocolAllowlist]) - // eslint-disable-next-line react-hooks/rules-of-hooks - const activeLocationDeps = React.useMemo( - () => - getActiveLocationDeps( - activeOptions, - next, - !!externalLink, - ), - // TODO: do we need full `next` here? or could we re-compute this only when next.search changes? - // eslint-disable-next-line react-hooks/exhaustive-deps -- next is tracked as its properties - [activeOptions, externalLink, next.hash, next.pathname, next.search], - ) - - // eslint-disable-next-line react-hooks/rules-of-hooks - React.useLayoutEffect(() => { - buildLocationRef.current = buildLocation - activeLocationDepsRef.current = activeLocationDeps - }, [activeLocationDeps, buildLocation]) - // eslint-disable-next-line react-hooks/rules-of-hooks const isActive = React.useMemo(() => { if (externalLink) return false @@ -805,13 +783,6 @@ type BuildLocationState = { options: unknown } -type ActiveLocationDeps = { - deps: number - expectedSearchCount: number - ignoreUndefined: boolean - searchKeys?: ReadonlyArray -} - const BUILD_LOCATION_DEP_NONE = 0 const BUILD_LOCATION_DEP_PATHNAME = 1 const BUILD_LOCATION_DEP_SEARCH = 2 @@ -819,18 +790,6 @@ const BUILD_LOCATION_DEP_HASH = 4 const BUILD_LOCATION_DEP_STATE = 8 const BUILD_LOCATION_DEP_ALL = 15 -const ACTIVE_LOCATION_SEARCH_COUNT_NONE = -1 - -const SEARCH_EXPLICIT_UNDEFINED_OPTIONS = { - ignoreUndefined: false, -} as const - -const NO_ACTIVE_LOCATION_DEPS: ActiveLocationDeps = { - deps: BUILD_LOCATION_DEP_NONE, - expectedSearchCount: ACTIVE_LOCATION_SEARCH_COUNT_NONE, - ignoreUndefined: true, -} - const composeHandlers = (handlers: Array>) => (e: React.SyntheticEvent) => { @@ -878,83 +837,37 @@ function didLocationChange( ) } -function getActiveLocationDeps( - activeOptions: LinkOptions['activeOptions'], - nextLocation: Pick, - externalLink: boolean, -): ActiveLocationDeps { - if (externalLink) { - return NO_ACTIVE_LOCATION_DEPS +function canReuseBuildLocation(options: { + from?: unknown + hash?: unknown + mask?: unknown + params?: unknown + search?: unknown + state?: unknown + to?: unknown +}) { + if (options.mask) { + return false } - const exact = activeOptions?.exact ?? false - const includeSearch = activeOptions?.includeSearch ?? true - const includeHash = !!activeOptions?.includeHash - const ignoreUndefined = !activeOptions?.explicitUndefined - const searchKeys = includeSearch - ? getSearchKeys(nextLocation.search, ignoreUndefined) - : undefined - - return { - deps: - BUILD_LOCATION_DEP_PATHNAME | (includeHash ? BUILD_LOCATION_DEP_HASH : 0), - expectedSearchCount: - includeSearch && exact - ? (searchKeys?.length ?? 0) - : ACTIVE_LOCATION_SEARCH_COUNT_NONE, - ignoreUndefined, - searchKeys: searchKeys?.length ? searchKeys : undefined, - } -} - -function didActiveLocationChange( - prev: ParsedLocation, - next: ParsedLocation, - deps: ActiveLocationDeps, -) { if ( - deps.deps & BUILD_LOCATION_DEP_PATHNAME && - prev.pathname !== next.pathname + isInherit(options.search) || + isInherit(options.params) || + isInherit(options.hash) || + isInherit(options.state) ) { - return true + return false } - if (deps.searchKeys?.length) { - const prevSearch = prev.search as Record - const nextSearch = next.search as Record - const deepEqualOptions = deps.ignoreUndefined - ? undefined - : SEARCH_EXPLICIT_UNDEFINED_OPTIONS - - for (const key of deps.searchKeys) { - if (!deepEqual(prevSearch?.[key], nextSearch?.[key], deepEqualOptions)) { - return true - } - } + if (typeof options.to !== 'string') { + return false } - if (deps.expectedSearchCount !== ACTIVE_LOCATION_SEARCH_COUNT_NONE) { - if ( - getSearchKeys(prev.search, deps.ignoreUndefined).length !== - getSearchKeys(next.search, deps.ignoreUndefined).length - ) { - return true - } - } - - return !!(deps.deps & BUILD_LOCATION_DEP_HASH && prev.hash !== next.hash) + return options.to.charCodeAt(0) === 47 && options.to.charCodeAt(1) !== 47 } -function getSearchKeys(search: Record, ignoreUndefined: boolean) { - const keys = [] as Array - - for (const key in search) { - if (!ignoreUndefined || search[key] !== undefined) { - keys.push(key) - } - } - - return keys +function isInherit(p: unknown) { + return p === true || typeof p === 'function' } type UseLinkReactProps = TComp extends keyof React.JSX.IntrinsicElements diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 483fbfe0c1..9ee884d9fb 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1859,9 +1859,7 @@ export class RouterCore< if ( locationDepsTarget && - dest.params !== false && - dest.params !== null && - nextTo.includes('$') + pathRequiresCurrentParams(nextTo, dest.params) ) { locationDeps |= BUILD_LOCATION_DEP_PATHNAME } @@ -3114,6 +3112,10 @@ function routeNeedsCurrentSearch( ) } +function pathRequiresCurrentParams(nextTo: string, params: unknown) { + return params !== false && nextTo.includes('$') +} + function buildMiddlewareChain(destRoutes: ReadonlyArray) { const context = { dest: null as unknown as BuildNextOptions,