Add a few more setup configurations to measure the number of `__store`
updates:
- with caching (`staleTime > 0`)
- when preloading multiple times the same route (simulates hovering a
list of links to the same page w/ different params)
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
It turns out the 'hover preload, then navigate, w/ async loaders' test
in
`packages/react-router/tests/store-updates-during-navigation.test.tsx`
was sometimes (but very rarely) yielding 16 updates instead of the
expected 15. This PR makes minimal changes to this test so that it's now
reliably 14.
I'm not exactly sure where we lost that 1 update, so we might not be
measuring exactly the same thing. But it's still worth it to have a
robust test suite.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Tests**
* Improved reliability of hover preloading and navigation behavior tests
by introducing realistic loader delays and aligning interaction timing,
reducing flakiness.
* Updated assertions for store updates during navigation to reflect
observed behavior, ensuring more stable and predictable test outcomes.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Some minor performance improvements in `scroll-restoration.ts`
- in `getCssSelector`:
- we can obtain `indexOf` without creating an empty array through
`Array.prototype.indexOf`
- using `.unshift` in a loop is always bad for performance. To build
arrays in reverse, use `.push()` in the loop, and `.reverse()` at the
end.
- in `restoreScroll`:
- we can early exit without creating an IIFE by using a [labeled
statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label)
- we can avoid creating an array of elements to iterate over since we
already have an array
- in `onScroll`:
- we can avoid accessing the same key twice by using the `||=` operator
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- New Features
- None
- Bug Fixes
- More reliable scroll restoration after navigation and refresh.
- Improved handling of URL hash anchors for accurate in-page scrolling.
- Consistent scroll-to-top behavior across configured elements.
- Avoids runtime errors when session storage is unavailable or data is
invalid.
- Refactor
- Streamlined scroll handling and state initialization for improved
stability and minor performance gains.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Fix https://github.com/TanStack/router/pull/4971#discussion_r2282953542
With the code now simplified by previous PRs, we noticed that the
`shouldExecuteBeforeLoad` guard is always true, so we can clean it up.
In a follow up PR, we'll revise the conditions under which a
`beforeLoad` should be called or skipped.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Refactor**
* Streamlined pre-load checks and execution flow, reducing branching and
improving consistency across client and server rendering.
* Unified orchestration of the before-load phase to simplify control
flow and improve maintainability.
* **Bug Fixes**
* More reliable handling of redirects and “not found” states during
preloading, preventing unintended execution paths and improving
navigation stability.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Wait for this PR before merging:
https://github.com/TanStack/router/pull/4987. It adds unit tests that
should help make sure we're not breaking anything here.
---
The functions used to serialize and deserialize search params are called
*a lot*, but they are creating many unnecessary objects. This PR
refactors
- `encode` to be only as generic as what we need => in practice we only
need to handle 1 value per key (i.e. `.set()` and not `.append()`) so we
don't need a special case for arrays
- `decode` can avoid creating many arrays
- `stringifySearchWith` (and `defaultStringifySearch`) don't need to
pre-stringify the input into a `<string,string>` dictionary as `encode`
now accepts a stringifier function
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- Breaking Changes
- Removed encode and decode from React Router and Solid Router public
exports.
- Query string prefix support removed in encode/decode.
- Refactor
- Updated query string handling: arrays encode as comma-separated
values; duplicate keys decode into arrays.
- Streamlined error handling and avoided input mutation; consistent
leading “?” management.
- Tests
- Updated tests to match new encoding/decoding behavior and removed
prefix-related cases.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Just some tests for `defaultParseSearch` and `defaultStringifySearch`,
because they're used a lot and are very public and can handle user
inputs (as in final human users, not devs).
These tests are just documentation of the current behavior.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Tests**
* Added a comprehensive test suite for URL query-string
serialization/deserialization covering empty values, primitives,
complex/nested structures, special characters, circular/self-references,
and unusual inputs (e.g., Number/String objects, Promise, Date).
* Verifies round-trip isomorphism and behavior when parsing externally
sourced or malformed query strings.
* No public API changes and no user-facing changes.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Creating a `URL` object is a little expensive, and we know it's going to
throw if `href` is not a string. So we can skip it entirely in that case
(which is probably most cases?).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Bug Fixes**
* Improved redirect handling to avoid errors when a URL is missing or
invalid.
* Added safeguards to prevent runtime crashes when redirect data is
null.
* Enhanced URL parsing reliability during redirects.
* No changes to public APIs.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Based on the current usage of `pick`, directly addinf the picked keys to
the objects will be less overhead with the same result.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- Refactor
- Simplified internal routing logic related to navigation options; no
change to runtime behavior.
- Chores
- Removed an internal utility no longer used.
- Public API
- One non-essential utility export was removed from package entry
points, slightly reducing the public API surface.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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}`.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## 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.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
The pattern of copying an array just to `.reverse()` it and iterate it
from the end ends up creating a transient object (a copy of the array)
that needs to be garbage collected.
For example:
```ts
[...array].reverse().find(() => {/*...*/})
```
or
```ts
[...array].reverse().forEach(() => {/*...*/})
```
Instead we can use a regular `for` loop to iterate it from the end. This
will be mostly beneficial in `router-core > router > buildLocation` that
gets called pretty often.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- **Refactor**
- Improved head metadata processing in React and Solid routers to be
more efficient and readable, reducing work for large route metadata
sets.
- Simplified route matching logic to consistently pick the last relevant
match, improving clarity and maintainability.
- **Chores**
- Added a utility to locate the last list item meeting a condition,
supporting cleaner routing internals.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
some miscellaneous minor optimizations in the `loadMatches` pipeline.
- try and reduce the number of times we call `getMatch`
- ~~`onReady` doesn't need to return a promise (because it's never used
as such)~~
actually some things fail without the artificially added microtask here
- don't create `beforeLoadPromise` if there is no `beforeLoad` option
anyway
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- Bug Fixes
- Improved NotFound and error handling to prevent unnecessary blocking
and ensure readiness triggers correctly.
- More reliable SSR and preload behavior across route transitions.
- Refactor
- Streamlined route loading with per-route stale-while-revalidate,
reducing redundant work and improving navigation responsiveness.
- Reduced internal lookups and clarified readiness semantics for more
predictable loading states.
- Public API
- onReady callback is now synchronous (no Promise), aligning with
updated readiness flow.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
After the "flattening" PR https://github.com/TanStack/router/pull/4961,
we now have a very clear *separate responsibility* the `Router` class is
handling: loading matches.
This PR proposes we split the code that handles "loading matches" into
its own `load-matches.ts` file, with the entry points being
- `loadMatches`
- `loadRouteChunk`
In future PRs, we might consider splitting other responsibilities out of
the 3k LoC `router.ts` file
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
The `loadMatches` has an unnecessary complicated async setup, probably
due to how complicated the function was before recent cleanups:
```ts
async function loadMatches() {
try {
await new Promise((resolve, reject) => {
;(async () => {
try {
// the logic
resolve()
} catch (err) {
reject(err)
}
})()
})
// after promise
} catch (err) {
// error handling
}
}
```
Aside from some scheduling differences due to unnecessary promises in
the above example, this can be simplified down to this:
```ts
async function loadMatches() {
try {
// the logic
// after promise
} catch (err) {
// error handling
}
}
```
This is what this PR does.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- New Features
- No user-facing changes.
- Refactor
- Simplified internal async flow for route loading, removing redundant
promise wrapping.
- Maintains existing behavior and public API; no action required from
users.
- More consistent error handling and slightly reduced overhead during
parallel loads.
- Improves maintainability and prepares the codebase for future
enhancements.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- **Bug Fixes**
- Routing now correctly handles bracketed dynamic segments with multiple
characters in paths. Contents like [userId] are preserved in full (no
longer truncated to a single character), ensuring accurate initial route
generation and consistent navigation behavior for dynamic routes.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Following https://github.com/TanStack/router/pull/4916,
https://github.com/TanStack/router/pull/4925,
https://github.com/TanStack/router/pull/4926, and
https://github.com/TanStack/router/pull/4928, this PR keeps reducing the
number of store updates (`__store.setState` through `updateMatch`).
We check the values we want to set in the store are *actually different*
from what is already in the store before calling `updateMatch`
---
In the `store-updates-during-navigation` test tracking the number of
executions of a `useRouterState > select` method during a navigation,
our main test case goes from **14 calls** without this PR, to **10
calls** with this PR. Most test cases show significant improvements as
well.
---
Should be a partial improvement of
https://github.com/TanStack/router/issues/4359
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Bug Fixes**
* Prevented loss of previously loaded data during navigation when a
loader yields no value.
* Stabilized preloading to avoid redundant updates and unnecessary state
churn.
* Improved loading-state cleanup after navigation, reducing flicker and
inconsistent “fetching” indicators.
* **Performance**
* Reduced unnecessary state updates and re-renders during and after
preloads/loads for smoother navigation.
* **Tests**
* Updated async navigation tests to reflect refined timing and
data-return behavior and added a helper to simulate delayed async
results.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Following https://github.com/TanStack/router/pull/4916, this PR keeps
reducing the number of store updates (`__store.setState` through
`updateMatch`).
Early bail out of route before load step if `route.options.beforeLoad`
is not defined
---
The `store-updates-during-navigation` test tracking the number of
executions of a `useRouterState > select` method during a navigation
goes from **17 calls** without this PR, to **14 calls** with this PR (or
even 13 calls if `beforeLoad` is synchronous).
---
Should be a partial improvement of
https://github.com/TanStack/router/issues/4359
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **New Features**
* Added a not-found helper and router options to configure a default Not
Found component and a default preload strategy.
* **Refactor**
* Streamlined the before-load lifecycle for more deterministic
pending-state updates, earlier pending-timeout readiness, clearer
parameter/search error surfacing, and adjusted context composition;
loader error timing is more conservative.
* **Tests**
* Expanded test coverage with new scenarios (sync before-load, not-found
flow, hover-preload/navigation) and updated navigation update
expectations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This PR *should* be a no-op. Just restructuring the code to have all the
functions used by `loadMatches` at the same level, instead of nested
callbacks. In order to still have access to the data that was previously
in scope because of nesting, we use a `innerLoadContext` object, which
is basically just the arguments of `loadMatches`, and a few mutables.
However, in order to do so, we have to rearrange promises in an area
that is sensitive to any microtask order change, and we did change some
of them. So this is not *really* a no-op, even though this does not
attempt any optimization.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- New Features
- Smoother navigations with predictable pending states and minimum
display durations.
- More consistent head/meta updates after route loading.
- Bug Fixes
- More reliable redirects and 404 handling, including during preloading
and SSR.
- Reduced UI flicker by refining pending and preloading behavior.
- Refactor
- Reworked the routing load pipeline for improved performance,
stability, and SSR behavior.
- Streamlined before-load steps for clearer, more consistent execution.
- Tests
- Updated tests to reflect the new loading flow.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Following https://github.com/TanStack/router/pull/4916 and
https://github.com/TanStack/router/pull/4925, this PR keeps reducing the
number of store updates (`__store.setState` through `updateMatch`).
Reduce amount of work in `runLoader`:
- don't `updateMatch` to set `isFetching: 'loader'` if we know the
entire function will be synchronous
- don't await `route.options.loader()` if it is synchronous
- don't update store with `loaderData` if `route.options.loader` is not
defined
- don't `await route._lazyPromise` if it has already resolved
- don't `await route._componentsPromise` if it has already resolved
- don't `await minPendingPromise` if it is not defined or has already
resolved
For a sync `loader`, with already loaded route chunks, `runLoader`
should be synchronous and trigger a single `updateMatch` call.
---
The `store-updates-during-navigation` test tracking the number of
executions of a `useRouterState > select` method during a navigation
goes from **19 calls** without this PR, to **17 calls** with this PR.
---
Should be a partial improvement of
https://github.com/TanStack/router/issues/4359
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Minor cleanup of `handleRedirectAndNotFound` in `router-core`. The code
looked like there were 3 possible cases, but `err` is only handled if
it's a redirect or a notFound.
This PR is a no-op, it's just code cleanup without any functional
changes.
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Following https://github.com/TanStack/router/pull/4916, this PR keeps
reducing the number of store updates (`__store.setState` through
`updateMatch`).
We can skip `route.options.head()`, `route.options.scripts()`, and
`route.options.headers()` calls, if they are not defined, and not even
call `updateMatch` after.
Additionally, `head`, `scripts` and `headers` are now called in
parallel. They don't depend on one another, and so there is no reason to
delay their execution by calling them serially.
---
This PR also fixes 2 issues:
- in `cancelMatch`, we were resetting the timeout id to `undefined`
**before** calling `clearTimeout()` with it
- `handleRedirectAndNotFound` is sometimes called w/ `match` being
`undefined` (in case of a redirecting match during preload), which went
undetected because of heavy `match!` assertions, and the many
`try/catch` blocks
---
With this PR, the `redirection in preload` test in
`store-updates-during-navigation` goes from **11 updates** during the
preload to **8 updates**.
---
Should be a partial improvement of
https://github.com/TanStack/router/issues/4359
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
The `store-updates-during-navigation.test.tsx` file tests how many times
`updateMatch` is called during a navigation (i.e. how many times the
store is updated, and all subscribers re-run).
In this PR we clean up this test file to allow us to more easily test
various navigation types. We also add a test for "redirection inside
beforeLoad" whose result will be improved by
https://github.com/TanStack/router/pull/4925
---------
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
- Mark the `global` property of `NotFoundError` as deprecated
- Add a description for `headers`
- Sort the properties in order
Signed-off-by: leesb971204 <leesb971204@gmail.com>