clear-react-router 2.5.4 → 2.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,19 +13,22 @@ There is no `RouterProvider` or provider hierarchy to manage. Simply render `<Ro
13
13
 
14
14
  It provides first-class support for:
15
15
 
16
- * Predictable routing
17
- * Built-in data loading
18
- * Route actions
19
- * Simple, provider-free architecture
20
- * Small, explicit API
16
+ - Predictable routing
17
+ - Built-in data loading
18
+ - Route actions
19
+ - Simple, provider-free architecture
20
+ - Small, explicit API
21
21
 
22
22
  > TL;DR? **[Try the live playground](https://clear-react-router.vercel.app/playground)** — no setup, click around.
23
23
 
24
+ > Need compile-time route safety and are okay with a build step, file-based route conventions, and a generated route tree in exchange? Check out
25
+ > [Clear Safe Router](https://github.com/AndrewBubnov/clear-safe-router) ([npm](https://www.npmjs.com/package/clear-safe-router)) —
26
+ > built on this runtime.
24
27
 
25
28
  ## Features
26
29
 
27
30
  - **Nested Routes** - Organize your UI with nested layouts and routes
28
- - **Route Layouts** - A `layout` declared on a route wraps it *and* every descendant (stacking outermost-first), keeping shared chrome and state alive across nested navigation
31
+ - **Route Layouts** - A `layout` declared on a route wraps it _and_ every descendant (stacking outermost-first), keeping shared chrome and state alive across nested navigation
29
32
  - **Data Loading** - Built-in loaders with TTL-based caching (`staleTime`)
30
33
  - **Navigation Blocking** - Prevent accidental navigation with `useBlocker`
31
34
  - **Smooth Animations** - Page transitions with fade effect (customizable duration)
@@ -34,7 +37,7 @@ It provides first-class support for:
34
37
  - **Cache invalidation** - Manual route invalidation
35
38
  - **Bounded Cache** - Automatically evicts least recently used entries once `maxCacheSize` is reached, keeping memory usage predictable in long sessions
36
39
  - **Cache inspection** - Opt into a live, read-only snapshot of cached loader entries with `enableCacheSnapshot` and `useCacheSnapshot()`
37
- - **Prefetching** - Preload data on hover; prefetched entries stay fresh for 30 seconds before the first navigation
40
+ - **Prefetching** - Preload data on hover; prefetched entries of router-cached routes stay fresh for 30 seconds before the first navigation, while `externalCache` routes re-run their loader every time
38
41
  - **Lazy Loading** - Code-split your routes with dynamic imports for optimal performance
39
42
  - **Scroll Restoration** — Automatically saves and restores scroll position when navigating back to a page (preserves user's scroll position)
40
43
  - **Optimistic navigation** — Instantly renders stale cached data while fresh data is loaded in the background.
@@ -64,27 +67,28 @@ The host rewrite only serves the app shell. To render your own UI for unknown cl
64
67
 
65
68
  ### `Router`
66
69
 
67
- | Prop | Type | Default | Description |
68
- |------|------|---------|-------------|
69
- | `routes` | `RouteItem[]` | required | Array of route configurations |
70
- | `maxCacheSize` | `number \| undefined` | 60 for mobile, 150 for desktop | Maximum number of cached loader entries. Once the limit is reached, the least recently used entries are evicted |
71
- | `isAnimated` | `boolean \| undefined` | `false` | Enable smooth page fade transitions |
72
- | `animationDuration` | `number \| undefined` | `optional` | Animation duration in milliseconds (browser default is used if not set) |
73
- | `context` | `object` | `{}` | Initial context (user, theme, etc.) |
74
- | `errorBoundary` | `ComponentType<{ children: ReactNode }>` | `undefined` | Custom error boundary component for catching render errors in route components |
75
- | `defaultMinLoaderDuration` | `number \| undefined` | `0` | Default minimum time the loader fallback stays visible, to avoid flickering |
76
- | `defaultLoaderFallback` | `ReactElement \| () => ReactElement` | `optional` | Default loading fallback for every route loader |
77
- | `defaultErrorElement` | `ReactElement \| () => ReactElement` | `optional` | Default error fallback for every route |
78
- | `defaultRetry` | `number \| { count: number; delay: number }` | `optional` | Default cache revalidation retry policy for all routes |
79
- | `defaultStaleTime` | `number` | `0` | Default time in milliseconds before cached loader data is considered stale. When unset (or `0`), data is stale immediately and navigation revalidates it |
80
- | `defaultBeforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
81
- | `defaultAfterLoad` | `({ params, context, searchParams }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
82
- | `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
83
- | `defaultHoverPrefetchDelay` | `number \| undefined` | `150` | Default delay in milliseconds before prefetching on hover (only for `'hover'` strategy) |
84
- | `defaultScrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | `auto` | Default scroll restoration behavior |
85
- | `revalidateOnFocus` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser tab regains focus |
86
- | `revalidateOnReconnect` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser regains an internet connection |
87
- | `enableCacheSnapshot` | `boolean` | `false` | Enables cache snapshot tracking for [`useCacheSnapshot()`](#usecachesnapshot). Off by default: no snapshot is built and the hook returns an empty list |
70
+ | Prop | Type | Default | Description |
71
+ | ---------------------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
72
+ | `routes` | `RouteItem[]` | required | Array of route configurations |
73
+ | `maxCacheSize` | `number \| undefined` | 60 for mobile, 150 for desktop | Maximum number of cached loader entries. Once the limit is reached, the least recently used entries are evicted |
74
+ | `isAnimated` | `boolean \| undefined` | `false` | Enable smooth page fade transitions |
75
+ | `animationDuration` | `number \| undefined` | `optional` | Animation duration in milliseconds (browser default is used if not set) |
76
+ | `context` | `object` | `{}` | Initial context (user, theme, etc.). Merged over the current context whenever the prop changes — loader `setContext` updates on other keys survive a re-render with a new inline object; on key collisions the prop wins |
77
+ | `errorBoundary` | `ComponentType<{ children: ReactNode }>` | `undefined` | Custom error boundary component for catching render errors in route components |
78
+ | `defaultMinLoaderDuration` | `number \| undefined` | `0` | Default minimum time the loader fallback stays visible, to avoid flickering |
79
+ | `defaultLoaderFallback` | `ReactElement \| () => ReactElement` | `optional` | Default loading fallback for every route loader |
80
+ | `defaultErrorElement` | `ReactElement \| () => ReactElement` | `optional` | Default error fallback for every route |
81
+ | `defaultRetry` | `number \| { count: number; delay: number }` | `optional` | Default cache revalidation retry policy for all routes |
82
+ | `defaultStaleTime` | `number` | `0` | Default time in milliseconds before cached loader data is considered stale. When unset (or `0`), data is stale immediately and navigation revalidates it |
83
+ | `defaultExternalCache` | `boolean` | `undefined` | `externalCache` fallback for routes that don't declare it. Marks routes whose data freshness is owned by the loader's source (e.g. TanStack Query): the router cache stores values but never claims freshness, so every navigation re-runs the loader |
84
+ | `defaultBeforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
85
+ | `defaultAfterLoad` | `({ params, context, searchParams }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
86
+ | `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
87
+ | `defaultHoverPrefetchDelay` | `number \| undefined` | `150` | Default delay in milliseconds before prefetching on hover (only for `'hover'` strategy) |
88
+ | `defaultScrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | `auto` | Default scroll restoration behavior |
89
+ | `revalidateOnFocus` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser tab regains focus |
90
+ | `revalidateOnReconnect` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser regains an internet connection |
91
+ | `enableCacheSnapshot` | `boolean` | `false` | Enables cache snapshot tracking for [`useCacheSnapshot()`](#usecachesnapshot). Off by default: no snapshot is built and the hook returns an empty list |
88
92
 
89
93
  > **Note:** Global lifecycle hooks wrap every route navigation. The global `defaultBeforeLoad` runs **before** the route-specific beforeLoad, while the global `defaultAfterLoad` runs **after** the route-specific afterLoad.
90
94
 
@@ -94,59 +98,109 @@ Required: `<Router>` expects the output of `createRouter` (`RouteItem[]` with bu
94
98
 
95
99
  Normalizes route configuration. Extracts dynamic params, builds nested paths.
96
100
 
97
- | Property | Type | Description |
98
- |----------|------|-------------|
99
- | `path` | `string` | Route path, e.g., `/user/:userId`. A child path is appended to the parent pattern — see [Nested routes](#nested-routes) |
100
- | `element` | `ReactElement \| () => ReactElement \| LazyComponent` | Component to render |
101
- | `layout` | Component that accepts `children` | Wraps this route's element and is inherited by every descendant route. A descendant's own `layout` nests *inside* the inherited ones (see [Layouts](#layouts)) |
102
- | `beforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | Runs before every route navigation. Auth checks and redirects. Can update context via `setContext`. `redirect` is provided by the router |
103
- | `loader` | `({ params, context, setContext, searchParams, signal }) => Promise<unknown>` | Fetch data using route params, search params, abort controller signal and context. Can update context via `setContext` |
104
- | `afterLoad` | `({ params, context, searchParams }) => Promise<void> \| void` | Runs after a successful navigation once the route has finished loading. Analytics, side effects after data is loaded. Can update context via `setContext` |
105
- | `minLoaderDuration` | `number \| undefined` | `undefined` | Minimum time the loader fallback stays visible, to avoid flickering |
106
- | `fallback` | `ReactElement \| () => ReactElement` | Loading fallback (for lazy loading) |
107
- | `loaderFallback` | `ReactElement \| () => ReactElement` | Loading fallback for the route's `loader`. Overrides the global `Router.defaultLoaderFallback` |
108
- | `retry` | `number \| { count: number; delay: number }` | Overrides the global cache revalidation retry policy for this route |
109
- | `optimistic` | `boolean \| undefined` | Instant navigation using stale data while fresh data is loaded in the background |
110
- | `errorElement` | `ReactElement \| () => ReactElement \| LazyComponent` | Error fallback for the route. Overrides the global `Router.defaultErrorElement` |
111
- | `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, data is stale immediately and navigation revalidates it. Use `Infinity` to never consider it stale |
112
- | `gcTime` | `number \| undefined` | How long, in milliseconds, an unused cache entry is kept in memory after you navigate away, before it's garbage-collected |
113
- | `actions` | `({ params, context, searchParams, setContext, location }) => Record<string, (data: Record<string, unknown>) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. |
114
- | `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active. Each tick refetches unconditionally, ignoring `staleTime` |
115
- | `scrollRestoration` | `boolean \| string[] \| undefined` | Restore scroll position when navigating back to this route. `true` restores the window scroll; a string array restores scroll inside specific scrollable elements, matched by their `id` |
116
- | `scrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | Scroll restoration behavior |
101
+ > **Cache identity is canonical.** Trailing slashes collapse and query params are sorted and re-encoded, so `/users`, `/users/` and reordered query params share one cache entry — one loader run, one `optimistic` hit. The URL in the address bar is never rewritten: the cache key is normalized, your URL spelling stays.
102
+
103
+ > **Route matching is order-sensitive:** the first matching route wins. Declare static siblings (`/users/new`) before dynamic ones (`/users/:id`), and a `*` catch-all last — in dev mode a warning fires for a shadowed route, a same-shape duplicate, or a catch-all that is not last.
104
+
105
+ > Route options are **per-leaf**: each route's `staleTime`, `retry`, `gcTime`, etc. apply to that route only (app-wide defaults come from `<Router>` props). The only options inherited from a parent to all its descendants are `layout` and `externalCache` (a child can override either — including opting out with `externalCache: false`).
106
+
107
+ | Property | Type | Description |
108
+ | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
109
+ | `path` | `string` | Route path, e.g., `/user/:userId`. A child path is appended to the parent pattern — see [Nested routes](#nested-routes) |
110
+ | `element` | `ReactElement \| () => ReactElement \| LazyComponent` | Component to render |
111
+ | `layout` | Component that accepts `children` | Wraps this route's element and is inherited by every descendant route. A descendant's own `layout` nests _inside_ the inherited ones (see [Layouts](#layouts)) |
112
+ | `beforeLoad` | `({ params, context, redirect, setContext, location, signal }) => Promise<unknown> \| undefined \| void` | Runs before every route navigation. Auth checks and redirects. Can update context via `setContext`. `redirect` is provided by the router. `signal` aborts when the navigation is superseded — check it before long work or `setContext` |
113
+ | `loader` | `({ params, context, setContext, searchParams, signal }) => Promise<unknown>` | Fetch data using route params, search params, abort controller signal and context. Can update context via `setContext` |
114
+ | `afterLoad` | `({ params, context, searchParams }) => Promise<void> \| void` | Runs after a successful navigation once the route has finished loading. Analytics, side effects after data is loaded. Can update context via `setContext` |
115
+ | `minLoaderDuration` | `number \| undefined` | `undefined` | Minimum time the loader fallback stays visible, to avoid flickering |
116
+ | `fallback` | `ReactElement \| () => ReactElement` | Loading fallback (for lazy loading) |
117
+ | `loaderFallback` | `ReactElement \| () => ReactElement` | Loading fallback for the route's `loader`. Overrides the global `Router.defaultLoaderFallback` |
118
+ | `retry` | `number \| { count: number; delay: number }` | Overrides the global cache revalidation retry policy for this route |
119
+ | `optimistic` | `boolean \| undefined` | Instant navigation using stale data while fresh data is loaded in the background |
120
+ | `errorElement` | `ReactElement \| () => ReactElement \| LazyComponent` | Error fallback for the route. Overrides the global `Router.defaultErrorElement` |
121
+ | `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, data is stale immediately and navigation revalidates it. Use `Infinity` to never consider it stale |
122
+ | `externalCache` | `boolean \| undefined` | The route's data freshness is owned by the loader's source (e.g. an external cache like TanStack Query): the router cache stores values but never claims freshness, so every navigation re-runs the loader. Inherited by children; a child can opt out with `false` |
123
+ | `gcTime` | `number \| undefined` | How long, in milliseconds, an unused cache entry is kept in memory after you navigate away, before it's garbage-collected |
124
+ | `actions` | `({ params, context, searchParams, setContext, location }) => Record<string, (data: Record<string, unknown>) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. |
125
+ | `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active. Each tick refetches unconditionally, ignoring `staleTime` |
126
+ | `scrollRestoration` | `boolean \| string[] \| undefined` | Restore scroll position when navigating back to this route. `true` restores the window scroll; a string array restores scroll inside specific scrollable elements, matched by their `id` |
127
+ | `scrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | Scroll restoration behavior |
117
128
 
118
129
  `beforeLoad`, `loader` and `actions` receive:
119
130
 
120
131
  ```ts
121
132
  {
122
- params: Record<string, string>; // Route parameters
123
- context: Record<string, unknown>; // Router context
124
- setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
125
- searchParams: Record<string, string>; // URL search parameters
126
- location: Location; // Route location
133
+ params: Record<string, string>; // Route parameters
134
+ context: Record<string, unknown>; // Router context
135
+ setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
136
+ searchParams: Record<string, string>; // URL search parameters
137
+ location: Location; // Route location
127
138
  }
128
139
  ```
140
+
129
141
  see [`Location`](#uselocation) and [`Where you came from`](#where-you-came-from) for type details
130
-
142
+
131
143
  `beforeLoad` additionally receives:
144
+
132
145
  ```ts
133
146
  {
134
- redirect: (arg: Location | string) => Promise<void>; // Programmatic redirection, see [redirect](#redirect)
147
+ redirect: (arg: Location | string) => Promise<void>; // Programmatic redirection, see [redirect](#redirect)
135
148
  }
136
149
  ```
150
+
137
151
  see [`redirect`](#redirect) for details on programmatic redirects
138
152
 
139
153
  > `beforeLoad` runs only for the route that matched the URL (plus the global `Router.defaultBeforeLoad`). It is **not inherited** from parent routes — put an auth guard on the leaf route or use `defaultBeforeLoad` for app-wide checks.
140
154
 
141
155
  `loader` additionally receives:
156
+
142
157
  ```ts
143
158
  {
144
- signal: AbortSignal; // Aborted if a newer navigation supersedes this one — pass to fetch() to cancel in-flight requests
145
- attempt: number; // 1-based attempt counter within this fetch: 1 on first try, 2+ on retries
159
+ signal: AbortSignal; // Aborted if a newer navigation supersedes this one — pass to fetch() to cancel in-flight requests
160
+ attempt: number; // 1-based attempt counter within this fetch: 1 on first try, 2+ on retries
146
161
  }
147
162
  ```
163
+
148
164
  > **Note:** `gcTime` is independent from `staleTime` — `staleTime` controls when cached data is considered outdated (and needs a refetch), while `gcTime` controls how long the cache entry stays in memory at all once you leave that route. Data can be fresh and still get garbage-collected, or stale and still linger in memory, depending on which you set. The timer starts only when you navigate away from the route and is cancelled if you come back before it fires — it isn't affected by prefetching. This is mainly useful for routes with heavy or fast-changing data (large tables, dashboards with charts) that you don't want lingering in memory indefinitely, even when `maxCacheSize` hasn't been reached yet.
149
- If a route is both `optimistic` and has `gcTime` set, keep in mind the cached snapshot can disappear while you're relying on it for an instant render — combine the two deliberately, not by default.
165
+ > If a route is both `optimistic` and has `gcTime` set, keep in mind the cached snapshot can disappear while you're relying on it for an instant render — combine the two deliberately, not by default.
166
+
167
+ ### External data cache (TanStack Query)
168
+
169
+ The router stays data-agnostic: a `loader` can delegate storage and freshness to an external cache (e.g. TanStack Query) passed through `<Router context={{ queryClient }}>`. One route flag keeps the router cache from outranking the external cache.
170
+
171
+ ```tsx
172
+ import { QueryClient } from '@tanstack/react-query';
173
+
174
+ // Single helper with the single legitimate cast: context is Record<string, unknown>.
175
+ const getQueryClient = (context: Record<string, unknown>): QueryClient => {
176
+ if (context.queryClient instanceof QueryClient) return context.queryClient;
177
+ throw new Error('getQueryClient: router context has no queryClient');
178
+ };
179
+
180
+ const productLoader = ({ context, params }: { context: Record<string, unknown>; params: Record<string, string> }) =>
181
+ getQueryClient(context).query({
182
+ queryKey: ['product', params.productId],
183
+ queryFn: () => fetchProduct(params.productId),
184
+ staleTime: 5000,
185
+ });
186
+ ```
187
+
188
+ The contract:
189
+
190
+ - `queryClient.query()` resolves from the query cache while the fact is fresh and **awaits a refetch once stale**. The queryKey is **fact identity** (`['product', id]`), not route identity — that is where cross-route fact sharing comes from.
191
+ - Never `ensureQueryData`: in query-core 5.108 it returns cached data whenever it exists regardless of staleness (refetch only via `revalidateIfStale`, still resolving cached) and it is `@deprecated` → use `queryClient.query()`.
192
+ - `<QueryClientProvider client={queryClient}>` wraps the app for components (`useQuery`, `useMutation`); loaders and actions get the client through router context alone.
193
+ - Rules: flag the external section `externalCache: true` — the router cache then stores values but never claims freshness there, so route `staleTime` no longer decides freshness on it (and a global `defaultStaleTime` cannot leak in; `gcTime` still governs eviction). Invalidate **facts** from actions (`queryClient.invalidateQueries({ queryKey: ['product', id] })`), not URLs; router `invalidate()` after a TQ invalidate is optional (it only re-runs loaders — use it solely to refresh the loader snapshot while staying on the page); mutations are TQ primitives.
194
+
195
+ The prefetch window and the `externalCache` flag:
196
+
197
+ - By default a prefetched snapshot stays fresh for 30 seconds, so the first navigation reuses it **without running the loader** — TanStack Query is never consulted, and a fact invalidated between hover and click renders stale. This is the one place the router cache outranks the external cache.
198
+ - The fix is one declaration, not disabling prefetch: flag the external section `externalCache: true` (or `defaultExternalCache` on `<Router>` for every route). Hover prefetch still runs the loader and warms the external cache; **every** navigation re-runs the loader, which resolves from the external cache — the router cache stores values but never claims freshness. What this restores is the division of labor: **facts belong to the external cache; the render snapshot belongs to the router.** The router keeps owning its snapshot's `staleTime`/`gcTime`/`optimistic` — they operate on its copy of the value and no longer outrank the fact.
199
+ - For mixed apps (some routes on TanStack Query, some on the router cache), a Router-level default marks router-cache routes too (every navigation refetches) — flag sections instead. The flag is inherited by a section's children (like `layout`), and a child can opt out with `externalCache: false`.
200
+
201
+ > **Note:** prefetched entries of ordinary routes keep the built-in grace (30s, never shortened by the route's own window) and report it through `useCacheSnapshot()`. Entries of `externalCache` routes are never fresh — the entry is stored with `staleTime: 0`, so the snapshot reports `0` too. An explicit route value beats the `<Router>` default.
202
+
203
+ Honest limits: `staleTime`/`gcTime`/`optimistic` still operate on the router's **copy** of the loader value (the optimistic snapshot renders the router-cache entry; the gc timer still evicts) — they no longer decide external freshness. See the [playground demo](https://clear-react-router.vercel.app/playground/cache/external/CLR) for the live behavior.
150
204
 
151
205
  ### Nested routes
152
206
 
@@ -154,14 +208,14 @@ A child `path` is **appended to the parent pattern**. Write only the new segment
154
208
 
155
209
  ```tsx
156
210
  const routes = createRouter([
157
- {
158
- path: '/projects',
159
- element: <Projects />,
160
- children: [
161
- { path: ':projectId', element: <Project /> }, // -> /projects/:projectId
162
- { path: 'new', element: <NewProject /> }, // -> /projects/new
163
- ],
164
- },
211
+ {
212
+ path: '/projects',
213
+ element: <Projects />,
214
+ children: [
215
+ { path: ':projectId', element: <Project /> }, // -> /projects/:projectId
216
+ { path: 'new', element: <NewProject /> }, // -> /projects/new
217
+ ],
218
+ },
165
219
  ]);
166
220
  ```
167
221
 
@@ -183,9 +237,9 @@ Add one route with `path: '*'` as the **last** entry. It matches any depth:
183
237
 
184
238
  ```tsx
185
239
  const routes = createRouter([
186
- { path: '/', element: <Home /> },
187
- // ...other routes
188
- { path: '*', element: <NotFound /> },
240
+ { path: '/', element: <Home /> },
241
+ // ...other routes
242
+ { path: '*', element: <NotFound /> },
189
243
  ]);
190
244
  ```
191
245
 
@@ -193,40 +247,40 @@ const routes = createRouter([
193
247
 
194
248
  ### Layouts
195
249
 
196
- A route can declare a `layout`: a component that wraps the route's element and is **inherited by every descendant route**. Layouts **stack**: a descendant's own `layout` nests *inside* the inherited ones, outermost first. Use it for chrome and state that must survive navigation within a subtree — an app shell, a section navbar, tabs, a scroll container, a wizard.
250
+ A route can declare a `layout`: a component that wraps the route's element and is **inherited by every descendant route**. Layouts **stack**: a descendant's own `layout` nests _inside_ the inherited ones, outermost first. Use it for chrome and state that must survive navigation within a subtree — an app shell, a section navbar, tabs, a scroll container, a wizard.
197
251
 
198
252
  ```tsx
199
253
  const AppShell = ({ children }: { children: ReactNode }) => (
200
- <div className="shell">
201
- <TopNav />
202
- {children}
203
- </div>
254
+ <div className="shell">
255
+ <TopNav />
256
+ {children}
257
+ </div>
204
258
  );
205
259
 
206
260
  const SectionLayout = ({ children }: { children: ReactNode }) => (
207
- <div className="section">
208
- <SectionNav />
209
- {children}
210
- </div>
261
+ <div className="section">
262
+ <SectionNav />
263
+ {children}
264
+ </div>
211
265
  );
212
266
 
213
267
  const routes = createRouter([
214
- {
215
- path: '/',
216
- element: <Home />,
217
- layout: AppShell, // outermost: wraps everything under /
218
- children: [
219
- {
220
- path: '/settings',
221
- element: <SettingsHome />,
222
- layout: SectionLayout, // nests inside AppShell
223
- children: [
224
- { path: '/profile', element: <Profile /> }, // AppShell ⊃ SectionLayout ⊃ Profile
225
- { path: '/billing', element: <Billing />, layout: BillingLayout }, // AppShell ⊃ SectionLayout ⊃ BillingLayout ⊃ Billing
226
- ],
227
- },
228
- ],
229
- },
268
+ {
269
+ path: '/',
270
+ element: <Home />,
271
+ layout: AppShell, // outermost: wraps everything under /
272
+ children: [
273
+ {
274
+ path: '/settings',
275
+ element: <SettingsHome />,
276
+ layout: SectionLayout, // nests inside AppShell
277
+ children: [
278
+ { path: '/profile', element: <Profile /> }, // AppShell ⊃ SectionLayout ⊃ Profile
279
+ { path: '/billing', element: <Billing />, layout: BillingLayout }, // AppShell ⊃ SectionLayout ⊃ BillingLayout ⊃ Billing
280
+ ],
281
+ },
282
+ ],
283
+ },
230
284
  ]);
231
285
  ```
232
286
 
@@ -249,30 +303,30 @@ Rule of thumb: `to` for plain URLs, `path` + `params` when you want the pattern
249
303
 
250
304
  Active matching: `'/'` matches only exactly `'/'`; any other target is active on exact match or — with the default `exact={false}` — on nested URLs too (`/settings` is active at `/settings/profile`). Pass `exact` on contextual links (for example a back-link to `/settings`) when a child URL should not keep the link active.
251
305
 
252
- | Prop | Type | Default | Description |
253
- |------|------|---------|-------------|
254
- | `to` | `string` | required (unless `path` is set) | Target path as a raw URL. Mutually exclusive with `path` |
255
- | `path` | `string` (route pattern) | required (unless `to` is set) | Route pattern with `:segments`, e.g. `/product/:productId`. Segments are filled from `params` |
256
- | `params` | `Record<string, string \| number>` | required if `path` has `:segments` | Values for the pattern segments (URL-encoded). A missing param throws at runtime |
257
- | `search` | `string \| Record<string, string \| number \| boolean \| null \| undefined> \| undefined` | `undefined` | Query string or object appended to the target path |
258
- | `state` | `unknown` | `undefined` | Arbitrary value attached to the navigation entry |
259
- | `as` | `(props: ElementProps<T>, state: { isActive: boolean; isPending: boolean }) => ReactElement` | renders `<a>` | Render function for using a custom element/component instead of the default <a>. Receives the props to spread onto your element (href, ref, event handlers, className, style, children) as the first argument, and `{ isActive, isPending }` as a separate second argument — kept separate so these values are never accidentally forwarded to the DOM |
260
- | `exact` | `boolean` | `false` | When `false`, the link is also considered active if the current URL starts with `to` (useful for nested routes) |
261
- | `prefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `Router` config | Override the global prefetch strategy |
262
- | `hoverPrefetchDelay` | `number` | `Router` config | Override the global hover delay |
263
- | `children` | `ReactNode` | required | Content to render inside the link |
264
- | `className` | `string \| ({ isActive, isPending }) => string` | `undefined` | CSS class name(s). Can be a function for dynamic styling |
265
- | `style` | `CSSProperties \| ({ isActive, isPending }) => CSSProperties` | `undefined` | Inline styles. Can be a function for dynamic styling |
266
- | `activeClassName` | `string` optional | `'active-link'` | Class name applied when the link matches the current URL |
267
- | `pendingClassName` | `string` optional | `'pending-link'` | Class name applied when the link's target is loading |
268
- | `beforeNavigate` | `() => Promise<void> \| undefined` | `undefined` | Callback fired before navigation |
306
+ | Prop | Type | Default | Description |
307
+ | -------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
308
+ | `to` | `string` | required (unless `path` is set) | Target path as a raw URL. Mutually exclusive with `path` |
309
+ | `path` | `string` (route pattern) | required (unless `to` is set) | Route pattern with `:segments`, e.g. `/product/:productId`. Segments are filled from `params` |
310
+ | `params` | `Record<string, string \| number>` | required if `path` has `:segments` | Values for the pattern segments (URL-encoded). A missing param throws at runtime |
311
+ | `search` | `string \| Record<string, string \| number \| boolean \| null \| undefined> \| undefined` | `undefined` | Query string or object appended to the target path |
312
+ | `state` | `unknown` | `undefined` | Arbitrary value attached to the navigation entry |
313
+ | `as` | `(props: ElementProps<T>, state: { isActive: boolean; isPending: boolean }) => ReactElement` | renders `<a>` | Render function for using a custom element/component instead of the default <a>. Receives the props to spread onto your element (href, ref, event handlers, className, style, children) as the first argument, and `{ isActive, isPending }` as a separate second argument — kept separate so these values are never accidentally forwarded to the DOM |
314
+ | `exact` | `boolean` | `false` | When `false`, the link is also considered active if the current URL starts with `to` (useful for nested routes) |
315
+ | `prefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `Router` config | Override the global prefetch strategy |
316
+ | `hoverPrefetchDelay` | `number` | `Router` config | Override the global hover delay |
317
+ | `children` | `ReactNode` | required | Content to render inside the link |
318
+ | `className` | `string \| ({ isActive, isPending }) => string` | `undefined` | CSS class name(s). Can be a function for dynamic styling |
319
+ | `style` | `CSSProperties \| ({ isActive, isPending }) => CSSProperties` | `undefined` | Inline styles. Can be a function for dynamic styling |
320
+ | `activeClassName` | `string` optional | `'active-link'` | Class name applied when the link matches the current URL |
321
+ | `pendingClassName` | `string` optional | `'pending-link'` | Class name applied when the link's target is loading |
322
+ | `beforeNavigate` | `() => Promise<void> \| undefined` | `undefined` | Callback fired before navigation |
269
323
 
270
324
  **State values:**
271
325
 
272
- | State | Type | Description |
273
- |-------|------|-------------|
274
- | `isActive` | `boolean` | `true` when the link's `to` matches the current URL considering `exact` value |
275
- | `isPending` | `boolean` | `true` when the target route is currently loading (loader is running) |
326
+ | State | Type | Description |
327
+ | ----------- | --------- | ----------------------------------------------------------------------------- |
328
+ | `isActive` | `boolean` | `true` when the link's `to` matches the current URL considering `exact` value |
329
+ | `isPending` | `boolean` | `true` when the target route is currently loading (loader is running) |
276
330
 
277
331
  ### Accessibility
278
332
 
@@ -282,7 +336,7 @@ Extra `data-*` and `aria-*` props passed to `<Link>` (e.g. `data-testid`, `aria-
282
336
 
283
337
  ```tsx
284
338
  <Link to="/about" aria-label="About section" data-testid="about-link">
285
- About
339
+ About
286
340
  </Link>
287
341
  ```
288
342
 
@@ -290,14 +344,14 @@ When using a custom element via `as`, these attributes arrive in `props` togethe
290
344
 
291
345
  ### Prefetch Strategies
292
346
 
293
- | Strategy | Behavior |
294
- |----------|----------|
295
- | `'hover'` | Prefetches when the user hovers over the link (with configurable delay) |
296
- | `'render'` | Prefetches immediately when the link is rendered |
347
+ | Strategy | Behavior |
348
+ | ------------ | -------------------------------------------------------------------------- |
349
+ | `'hover'` | Prefetches when the user hovers over the link (with configurable delay) |
350
+ | `'render'` | Prefetches immediately when the link is rendered |
297
351
  | `'viewport'` | Prefetches when the link enters the viewport (using Intersection Observer) |
298
- | `'none'` | No prefetching |
352
+ | `'none'` | No prefetching |
299
353
 
300
- > A prefetched entry is considered fresh for 30 seconds. The first navigation within that window reuses it without running the loader; after that, the route's normal `staleTime` applies (by default `0`, so the next revisit revalidates). A longer route `staleTime` is never shortened by prefetching.
354
+ > A prefetched entry is considered fresh for the built-in grace window (30 seconds; never shortened by the route's `staleTime`) unless the route is flagged `externalCache`, in which case every navigation re-runs the loader — see [External data cache](#external-data-cache-tanstack-query). The first navigation within the window reuses the entry without running the loader; after that, the route's normal `staleTime` applies (by default `0`, so the next revisit revalidates). A longer route `staleTime` is never shortened by prefetching.
301
355
 
302
356
  ### Custom elements via `as`
303
357
 
@@ -310,23 +364,19 @@ When using `as` to render a custom component instead of the default `<a>`, your
310
364
 
311
365
  ```tsx
312
366
  // ✅ correct — every prop is forwarded to the host element
313
- const Button = ({ children, ...props }: ElementProps<HTMLButtonElement>) => (
314
- <button {...props}>{children}</button>
315
- );
367
+ const Button = ({ children, ...props }: ElementProps<HTMLButtonElement>) => <button {...props}>{children}</button>;
316
368
 
317
369
  // ❌ wrong — ref, event handlers, and href are silently dropped
318
- const Button = ({ children }: { children: ReactNode }) => (
319
- <button>{children}</button>
320
- );
370
+ const Button = ({ children }: { children: ReactNode }) => <button>{children}</button>;
321
371
  ```
322
372
 
323
373
  If you only want to add or override specific props (e.g. add a `variant`), spread the received props first, then apply your own on top:
324
374
 
325
375
  ```tsx
326
376
  const Button = ({ children, ...props }: ElementProps<HTMLButtonElement>) => (
327
- <button {...props} className={`btn ${props.className ?? ''}`}>
328
- {children}
329
- </button>
377
+ <button {...props} className={`btn ${props.className ?? ''}`}>
378
+ {children}
379
+ </button>
330
380
  );
331
381
  ```
332
382
 
@@ -360,6 +410,7 @@ import { Button } from '@mui/material';
360
410
  To about page
361
411
  </Link>
362
412
  ```
413
+
363
414
  ### Styling link states with CSS
364
415
 
365
416
  Before reaching for `as`, check whether CSS is enough: active and loading states are already
@@ -370,25 +421,25 @@ screen readers) intact:
370
421
 
371
422
  ```tsx
372
423
  <Link to="/playground/settings" aria-label="Settings" className="gear-link">
373
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true">
374
- <path d="..." />
375
- </svg>
424
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true">
425
+ <path d="..." />
426
+ </svg>
376
427
  </Link>
377
428
  ```
378
429
 
379
430
  ```css
380
431
  /* Active page — no state plumbing needed */
381
432
  .gear-link[aria-current='page'] {
382
- color: steelblue;
433
+ color: steelblue;
383
434
  }
384
435
  /* CSS beats SVG presentation attributes (fill="none"), so this fills the icon: */
385
436
  .gear-link[aria-current='page'] svg {
386
- fill: steelblue;
387
- stroke: steelblue;
437
+ fill: steelblue;
438
+ stroke: steelblue;
388
439
  }
389
440
  /* Target is loading: */
390
441
  .gear-link[aria-busy='true'] {
391
- opacity: 0.6;
442
+ opacity: 0.6;
392
443
  }
393
444
  ```
394
445
 
@@ -441,6 +492,7 @@ Reach for `as` only when the element itself must change (a `<button>`, a UI-kit
441
492
  Settings
442
493
  </Link>
443
494
  ```
495
+
444
496
  **Important**: prefetch="render" should be used sparingly, as it preloads data immediately when the link is rendered, which may cause unnecessary network requests.
445
497
 
446
498
  ## Retry
@@ -494,10 +546,10 @@ Unlike many routing libraries, retry is **not limited to the initial loader exec
494
546
 
495
547
  The retry policy is applied to the router's **cache revalidation mechanism**, so it automatically works for every operation that reloads route data, including:
496
548
 
497
- * Initial route loading
498
- * Cache revalidation
499
- * `invalidate()`
500
- * `prefetch()`
549
+ - Initial route loading
550
+ - Cache revalidation
551
+ - `invalidate()`
552
+ - `prefetch()`
501
553
 
502
554
  This ensures consistent behavior regardless of how the data is being refreshed.
503
555
 
@@ -515,40 +567,39 @@ Function provided to `beforeLoad` for programmatic redirection.
515
567
  import type { createRouter } from 'clear-react-router';
516
568
 
517
569
  const routes = createRouter([
518
- {
519
- path: '/dashboard',
520
- element: <Dashboard />,
521
- beforeLoad: ({ context, redirect }) => {
522
- if (!context.isAuthorized) return redirect('/');
523
- },
524
- },
570
+ {
571
+ path: '/dashboard',
572
+ element: <Dashboard />,
573
+ beforeLoad: ({ context, redirect }) => {
574
+ if (!context.isAuthorized) return redirect('/');
575
+ },
576
+ },
525
577
  ]);
526
578
 
527
579
  const routes = createRouter([
528
- {
529
- path: '/dashboard',
530
- element: <Dashboard />,
531
- beforeLoad: ({ context, redirect }) => {
532
- if (!context.isAuthorized) return redirect({ pathname: '/login', state: { from: '/dashboard' } });
533
- },
534
- },
580
+ {
581
+ path: '/dashboard',
582
+ element: <Dashboard />,
583
+ beforeLoad: ({ context, redirect }) => {
584
+ if (!context.isAuthorized) return redirect({ pathname: '/login', state: { from: '/dashboard' } });
585
+ },
586
+ },
535
587
  ]);
536
588
 
537
589
  const routes = createRouter([
538
- {
539
- path: '/user/:userId',
540
- loader: async ({ params, context, setContext }) => {
541
- const user = await fetchUser(params.userId);
542
- setContext({ ...context, currentUser: user });
543
- return { user };
544
- },
545
- beforeLoad: async ({ context, setContext, redirect }) => {
546
- if (!context.token) return redirect('/login');
547
- setContext({ ...context, lastVisit: Date.now() });
548
- },
549
- }
590
+ {
591
+ path: '/user/:userId',
592
+ loader: async ({ params, context, setContext }) => {
593
+ const user = await fetchUser(params.userId);
594
+ setContext({ ...context, currentUser: user });
595
+ return { user };
596
+ },
597
+ beforeLoad: async ({ context, setContext, redirect }) => {
598
+ if (!context.token) return redirect('/login');
599
+ setContext({ ...context, lastVisit: Date.now() });
600
+ },
601
+ },
550
602
  ]);
551
-
552
603
  ```
553
604
 
554
605
  ### Usage with Parameters
@@ -559,29 +610,29 @@ The `loader`, `beforeLoad`, and `afterLoad` hooks receive `params` (extracted fr
559
610
  import type { createRouter } from 'clear-react-router';
560
611
 
561
612
  const routes = createRouter([
562
- {
563
- path: '/user/:userId',
564
- element: <UserProfile />,
565
- loader: async ({ params, context }) => {
566
- // params.userId is available from the URL
567
- const user = await fetchUser(params.userId);
568
- return { user };
569
- },
570
- beforeLoad: async ({ params, context, redirect }) => {
571
- // Authentication check
572
- if (!context.isAuthorized) {
573
- return redirect('/login');
574
- }
575
- // Validate parameter
576
- if (!params.userId || !isValidUserId(params.userId)) {
577
- return redirect('/users');
578
- }
579
- },
580
- afterLoad: ({ params, context }) => {
581
- // Analytics or side effects
582
- console.log(`User ${params.userId} loaded`);
583
- },
584
- },
613
+ {
614
+ path: '/user/:userId',
615
+ element: <UserProfile />,
616
+ loader: async ({ params, context }) => {
617
+ // params.userId is available from the URL
618
+ const user = await fetchUser(params.userId);
619
+ return { user };
620
+ },
621
+ beforeLoad: async ({ params, context, redirect }) => {
622
+ // Authentication check
623
+ if (!context.isAuthorized) {
624
+ return redirect('/login');
625
+ }
626
+ // Validate parameter
627
+ if (!params.userId || !isValidUserId(params.userId)) {
628
+ return redirect('/users');
629
+ }
630
+ },
631
+ afterLoad: ({ params, context }) => {
632
+ // Analytics or side effects
633
+ console.log(`User ${params.userId} loaded`);
634
+ },
635
+ },
585
636
  ]);
586
637
  ```
587
638
 
@@ -602,11 +653,11 @@ actions?: ({ params, context, searchParams, setContext, location }) => ({
602
653
 
603
654
  ```ts
604
655
  {
605
- params: Record<string, string>; // Route parameters
606
- context: Record<string, unknown>; // Router context
607
- setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
608
- searchParams: Record<string, string>; // URL search parameters
609
- location: Location; // Route location
656
+ params: Record<string, string>; // Route parameters
657
+ context: Record<string, unknown>; // Router context
658
+ setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
659
+ searchParams: Record<string, string>; // URL search parameters
660
+ location: Location; // Route location
610
661
  }
611
662
  ```
612
663
 
@@ -622,15 +673,15 @@ A record where each key is an action name and each value is a function accepting
622
673
  import { useSubmitAction } from 'clear-react-router';
623
674
 
624
675
  const CreateUserForm = () => {
625
- const { onSubmit, isSubmitting, error } = useSubmitAction('createUser');
626
-
627
- return (
628
- <form onSubmit={onSubmit}>
629
- <input name="email" disabled={isSubmitting} />
630
- <button disabled={isSubmitting}>Create</button>
631
- {error && <span>{error.message}</span>}
632
- </form>
633
- );
676
+ const { onSubmit, isSubmitting, error } = useSubmitAction('createUser');
677
+
678
+ return (
679
+ <form onSubmit={onSubmit}>
680
+ <input name="email" disabled={isSubmitting} />
681
+ <button disabled={isSubmitting}>Create</button>
682
+ {error && <span>{error.message}</span>}
683
+ </form>
684
+ );
634
685
  };
635
686
  ```
636
687
 
@@ -643,28 +694,28 @@ const { register, handleSubmit } = useForm<FormValues>();
643
694
  const { submit, isSubmitting } = useSubmitAction('createUser');
644
695
 
645
696
  <form onSubmit={handleSubmit(submit)}>
646
- <input {...register('email')} disabled={isSubmitting} />
647
- </form>
697
+ <input {...register('email')} disabled={isSubmitting} />
698
+ </form>;
648
699
  ```
649
700
 
650
701
  Arguments:
651
702
 
652
- | Argument | Type | Default | Description |
653
- |---|---|---|---|
654
- | `action` | `string` | — | The action key defined in the route's `actions` |
655
- | `options.onSuccess` | `(data: unknown) => void \| undefined` | `undefined` | Called after a successful submission |
656
- | `options.onError` | `(error: unknown) => void \| undefined` | `undefined` | Called if the action throws |
657
- | `options.autoReset` | `boolean \| undefined` | `true` | Reset the form element after a successful native submission (`onSubmit` only — has no effect on `submit`) |
703
+ | Argument | Type | Default | Description |
704
+ | ------------------- | --------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------- |
705
+ | `action` | `string` | — | The action key defined in the route's `actions` |
706
+ | `options.onSuccess` | `(data: unknown) => void \| undefined` | `undefined` | Called after a successful submission |
707
+ | `options.onError` | `(error: unknown) => void \| undefined` | `undefined` | Called if the action throws |
708
+ | `options.autoReset` | `boolean \| undefined` | `true` | Reset the form element after a successful native submission (`onSubmit` only — has no effect on `submit`) |
658
709
 
659
710
  Return value:
660
711
 
661
- | Field | Type | Description |
662
- |---|---|---|
663
- | `submit` | `(data: Record<string, unknown>) => Promise<{ data: unknown; error: Error \| null }>` | Runs the action directly, from any form data source |
664
- | `onSubmit` | `(evt: SubmitEvent<HTMLFormElement>) => Promise<void>` | Ready-made handler for a native `<form onSubmit={...}>` |
665
- | `data` | `unknown` | Result of the last successful submission |
666
- | `error` | `Error \| null` | Error from the last failed submission |
667
- | `isSubmitting` | `boolean` | `true` while the action is in flight |
712
+ | Field | Type | Description |
713
+ | -------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------- |
714
+ | `submit` | `(data: Record<string, unknown>) => Promise<{ data: unknown; error: Error \| null }>` | Runs the action directly, from any form data source |
715
+ | `onSubmit` | `(evt: SubmitEvent<HTMLFormElement>) => Promise<void>` | Ready-made handler for a native `<form onSubmit={...}>` |
716
+ | `data` | `unknown` | Result of the last successful submission |
717
+ | `error` | `Error \| null` | Error from the last failed submission |
718
+ | `isSubmitting` | `boolean` | `true` while the action is in flight |
668
719
 
669
720
  > The native `onSubmit` handler converts the form via `Object.fromEntries(new FormData(...))` —
670
721
  > if your form has multiple fields sharing the same `name` (checkbox groups, `<select multiple>`),
@@ -677,10 +728,10 @@ Return value:
677
728
 
678
729
  ### Arguments
679
730
 
680
- | Argument | Type | Description |
681
- |----------|------|-------------|
682
- | `action` | `string` | Name of the route action to execute. Must match a key returned from the route's `actions` configuration. |
683
- | `options` | `Options` | Optional callbacks invoked after the action succeeds or fails. |
731
+ | Argument | Type | Description |
732
+ | --------- | --------- | -------------------------------------------------------------------------------------------------------- |
733
+ | `action` | `string` | Name of the route action to execute. Must match a key returned from the route's `actions` configuration. |
734
+ | `options` | `Options` | Optional callbacks invoked after the action succeeds or fails. |
684
735
 
685
736
  ```ts
686
737
  type Options = { onSuccess?: (args: unknown) => void; onError?: (args: unknown) => void };
@@ -690,14 +741,13 @@ type Options = { onSuccess?: (args: unknown) => void; onError?: (args: unknown)
690
741
  const save = useAction('save');
691
742
  const handleClick = async () => await save({ data: 'Hello world!' });
692
743
 
693
- <button onClick={handleClick}>Save</button>
744
+ <button onClick={handleClick}>Save</button>;
694
745
  ```
695
746
 
696
747
  `useAction` automatically invalidates the route where the action was triggered after a successful action, causing `loader` to run again in the background. This remains the same route even if the user navigates away while the action is in flight.
697
748
 
698
749
  This hook is useful when the mutation is triggered programmatically, such as from dialogs, context menus, drag-and-drop interactions, keyboard shortcuts, or custom UI components.
699
750
 
700
-
701
751
  ### Error Boundaries
702
752
 
703
753
  You can provide a custom error boundary to catch rendering errors in route components. This is useful for preventing the entire app from crashing when a specific route fails to render.
@@ -707,8 +757,9 @@ import { Router } from 'clear-react-router';
707
757
  import { routes } from './routes';
708
758
  import { ErrorBoundary } from './components/ErrorBoundary';
709
759
 
710
- const App = () => <Router routes={routes} errorBoundary={ErrorBoundary} />
760
+ const App = () => <Router routes={routes} errorBoundary={ErrorBoundary} />;
711
761
  ```
762
+
712
763
  **Note:** The `errorBoundary` prop only catches render-time errors in route components. It does not catch errors in `loader` or `beforeLoad` — those are handled by the router's `errorElement` mechanism.
713
764
 
714
765
  ## Hooks
@@ -718,13 +769,17 @@ const App = () => <Router routes={routes} errorBoundary={ErrorBoundary} />
718
769
  Returns a function to navigate programmatically. Accepts a string (pathname, optionally with a `?query`), a `NavigationLocation` object (`pathname`, or typed `path` + `params` — see below), or `-1` to go back.
719
770
 
720
771
  ```tsx
721
- type NavigationLocation = { pathname: string; search?: string | Record<string, string | number | boolean | null | undefined>; state?: unknown }
772
+ type NavigationLocation = {
773
+ pathname: string;
774
+ search?: string | Record<string, string | number | boolean | null | undefined>;
775
+ state?: unknown;
776
+ };
722
777
 
723
778
  const navigate = useNavigate();
724
779
 
725
- navigate('/about'); // string
726
- navigate({ pathname: '/user/123', search: { user: 'Jane Doe' }, state: { from: 'home' } }); // NavigationLocation
727
- navigate(-1); // go back
780
+ navigate('/about'); // string
781
+ navigate({ pathname: '/user/123', search: { user: 'Jane Doe' }, state: { from: 'home' } }); // NavigationLocation
782
+ navigate(-1); // go back
728
783
  ```
729
784
 
730
785
  **Note:** Navigation state can be accessed via [`useLocation()`](#uselocation):
@@ -761,7 +816,7 @@ navigation, pass a route pattern via `path` with matching `params` instead — t
761
816
  interpolates the segments (values are URL-encoded, a missing param throws):
762
817
 
763
818
  ```tsx
764
- <Link path="/product/:productId" params={{ productId: '7' }} />
819
+ <Link path="/product/:productId" params={{ productId: '7' }} />;
765
820
  navigate({ path: '/product/:productId', params: { productId: '7' } });
766
821
  ```
767
822
 
@@ -772,7 +827,7 @@ Declarative and imperative forms are equivalent — this link:
772
827
 
773
828
  ```tsx
774
829
  <Link path="/nest/:nestId/item/:itemId" params={{ nestId, itemId }}>
775
- {itemId}
830
+ {itemId}
776
831
  </Link>
777
832
  ```
778
833
 
@@ -781,9 +836,7 @@ does the same as this button:
781
836
  ```tsx
782
837
  const navigate = useNavigate();
783
838
 
784
- <button onClick={() => navigate({ path: '/nest/:nestId/item/:itemId', params: { nestId, itemId } })}>
785
- {itemId}
786
- </button>
839
+ <button onClick={() => navigate({ path: '/nest/:nestId/item/:itemId', params: { nestId, itemId } })}>{itemId}</button>;
787
840
  ```
788
841
 
789
842
  Same type-checking, same interpolation. Use links for navigation, buttons with `navigate`
@@ -798,37 +851,38 @@ userland pattern — adopt it ladder-style, each rung optional:
798
851
  - **Rung 1 — `path` + `params` on plain `Link`.** No union, no wrapper, no setup:
799
852
  TypeScript infers the pattern from the `path` literal itself and checks `params`
800
853
  against it:
801
- ```tsx
802
- <Link path="/product/:productId" params={{ productId: '7' }} /> // ok
803
- <Link path="/product/:productId" /> // error: params missing
804
- <Link path="/product/:productId" params={{ id: '7' }} /> // error: wrong param name
805
- ```
806
- But path *existence* is unchecked — there is no list to check against, so this
807
- compiles silently:
808
- ```tsx
809
- <Link path="/playgroud/cache" /> // typo, no error (no union knows the routes)
810
- ```
811
- In other words: rung 1 checks internal consistency (`path` ↔ `params`), not the
812
- outside world (path ↔ app routes). That half needs a union — rung 3.
854
+ ```tsx
855
+ <Link path="/product/:productId" params={{ productId: '7' }} /> // ok
856
+ <Link path="/product/:productId" /> // error: params missing
857
+ <Link path="/product/:productId" params={{ id: '7' }} /> // error: wrong param name
858
+ ```
859
+ But path _existence_ is unchecked — there is no list to check against, so this
860
+ compiles silently:
861
+ ```tsx
862
+ <Link path="/playgroud/cache" /> // typo, no error (no union knows the routes)
863
+ ```
864
+ In other words: rung 1 checks internal consistency (`path` ↔ `params`), not the
865
+ outside world (path ↔ app routes). That half needs a union — rung 3.
813
866
  - **Rung 2 — thin wrapper, no union.** Gives the pattern a name without any type file:
814
- ```tsx
815
- import { Link, type LinkProps } from 'clear-react-router';
816
867
 
817
- export const AppLink = <T extends HTMLElement = HTMLAnchorElement>(props: LinkProps<T>) => (
818
- <Link {...props} />
819
- );
820
- ```
868
+ ```tsx
869
+ import { Link, type LinkProps } from 'clear-react-router';
870
+
871
+ export const AppLink = <T extends HTMLElement = HTMLAnchorElement>(props: LinkProps<T>) => <Link {...props} />;
872
+ ```
873
+
821
874
  - **Rung 3 — wrapper + union.** Binds one union for existence checking:
822
- ```tsx
823
- type AppPaths = '/cache' | '/product/:productId';
824
875
 
825
- export const AppLink = <T extends HTMLElement = HTMLAnchorElement>(props: LinkProps<T, AppPaths>) => (
826
- <Link {...props} />
827
- );
876
+ ```tsx
877
+ type AppPaths = '/cache' | '/product/:productId';
878
+
879
+ export const AppLink = <T extends HTMLElement = HTMLAnchorElement>(props: LinkProps<T, AppPaths>) => (
880
+ <Link {...props} />
881
+ );
828
882
 
829
- <AppLink path="/product/:productId" params={{ productId: '7' }} /> // ok
830
- <AppLink path="/playgroud/cache" /> // error: not in AppPaths
831
- ```
883
+ <AppLink path="/product/:productId" params={{ productId: '7' }} /> // ok
884
+ <AppLink path="/playgroud/cache" /> // error: not in AppPaths
885
+ ```
832
886
 
833
887
  The union is generated by script or hand-written.
834
888
  Keep it next to the routes so drift is visible in review; a forgotten path fails
@@ -837,16 +891,18 @@ compilation at usage (fail-closed), a leftover entry is harmless.
837
891
  ### `useLocation()`
838
892
 
839
893
  Returns current location `{ pathname, search, state }`.
894
+
840
895
  ```tsx
841
896
  type Location = {
842
897
  pathname: string;
843
898
  search?: string;
844
899
  state?: unknown;
845
900
  prevLocation?: Omit<Location, 'state' | 'prevLocation'>;
846
- }
901
+ };
847
902
 
848
903
  const { pathname, search, state } = useLocation();
849
904
  ```
905
+
850
906
  ### Where you came from
851
907
 
852
908
  Every `location` carries `prevLocation` — the pathname and search of the route you
@@ -856,16 +912,16 @@ navigated away from. Useful for a contextual "Back" link, or for redirect logic
856
912
  ```tsx
857
913
  const location = useLocation();
858
914
 
859
- <Link to={location.prevLocation?.pathname ?? '/'}>← Back</Link>
915
+ <Link to={location.prevLocation?.pathname ?? '/'}>← Back</Link>;
860
916
  ```
861
917
 
862
918
  ```tsx
863
919
  // beforeLoad
864
920
  beforeLoad: async ({ location, redirect }) => {
865
- if (!isAuthenticated && location.prevLocation?.pathname !== '/login') {
866
- await redirect('/login');
867
- }
868
- }
921
+ if (!isAuthenticated && location.prevLocation?.pathname !== '/login') {
922
+ await redirect('/login');
923
+ }
924
+ };
869
925
  ```
870
926
 
871
927
  > `prevLocation` reflects only the immediately preceding route — it doesn't accumulate
@@ -878,11 +934,11 @@ Returns the cached data loaded by the current route's `loader`, along with any e
878
934
 
879
935
  **Returns:**
880
936
 
881
- | Property | Type | Description |
882
- |----------|:----:|-------------|
883
- | `data` | `T` | The data returned from the route's `loader` |
884
- | `loaderError` | `Error \| null` | Error from the `loader` (if any) |
885
- | `beforeLoadError` | `Error \| null` | Error from the `beforeLoad` hook (if any) |
937
+ | Property | Type | Description |
938
+ | ----------------- | :-------------: | ------------------------------------------- |
939
+ | `data` | `T` | The data returned from the route's `loader` |
940
+ | `loaderError` | `Error \| null` | Error from the `loader` (if any) |
941
+ | `beforeLoadError` | `Error \| null` | Error from the `beforeLoad` hook (if any) |
886
942
 
887
943
  ```tsx
888
944
  const UserProfile = () => {
@@ -909,7 +965,6 @@ const UserProfile = () => {
909
965
  <Router routes={routes} maxCacheSize={200} />
910
966
  ```
911
967
 
912
-
913
968
  ### `useCacheSnapshot()`
914
969
 
915
970
  Returns a read-only snapshot of the loader cache — intended for devtools panels, debugging, and cache
@@ -919,36 +974,36 @@ monitoring. Requires `<Router enableCacheSnapshot>`; while the flag is off the s
919
974
  import { useCacheSnapshot } from 'clear-react-router';
920
975
 
921
976
  const CachePanel = () => {
922
- const entries = useCacheSnapshot();
923
-
924
- return (
925
- <ul>
926
- {entries.map(entry => (
927
- <li key={entry.path}>
928
- {entry.path} — {entry.reason ?? 'unknown'} —{' '}
929
- {entry.isCached ? (entry.isLoading ? 'revalidating' : 'cached') : 'loading'}
930
- </li>
931
- ))}
932
- </ul>
933
- );
977
+ const entries = useCacheSnapshot();
978
+
979
+ return (
980
+ <ul>
981
+ {entries.map(entry => (
982
+ <li key={entry.path}>
983
+ {entry.path} — {entry.reason ?? 'unknown'} —{' '}
984
+ {entry.isCached ? (entry.isLoading ? 'revalidating' : 'cached') : 'loading'}
985
+ </li>
986
+ ))}
987
+ </ul>
988
+ );
934
989
  };
935
990
 
936
- <Router routes={routes} enableCacheSnapshot />
991
+ <Router routes={routes} enableCacheSnapshot />;
937
992
  ```
938
993
 
939
994
  ```ts
940
995
  type CacheReason = 'navigation' | 'prefetch' | 'invalidate' | 'polling';
941
996
 
942
997
  type CacheSnapshotEntry = {
943
- path: string; // pathname + search
944
- data: unknown; // loader result; undefined while the first load is in flight
945
- timestamp: number; // when the entry was written (ms since epoch)
946
- staleTime: number | undefined; // effective staleTime: route value, default, or 0 when neither is set
947
- reason?: CacheReason; // what wrote the entry last
948
- gcExpiresAt: number | undefined; // GC deadline, if a GC timer is pending
949
- gcDuration: number | undefined; // the route's gcTime, for progress display
950
- isCached: boolean; // a loader result exists in memory (fresh or stale)
951
- isLoading: boolean; // a loader for this path is currently running
998
+ path: string; // pathname + search
999
+ data: unknown; // loader result; undefined while the first load is in flight
1000
+ timestamp: number; // when the entry was written (ms since epoch)
1001
+ staleTime: number | undefined; // effective freshness window: prefetch grace, route/default staleTime, or 0 for externalCache
1002
+ reason?: CacheReason; // what wrote the entry last
1003
+ gcExpiresAt: number | undefined; // GC deadline, if a GC timer is pending
1004
+ gcDuration: number | undefined; // the route's gcTime, for progress display
1005
+ isCached: boolean; // a loader result exists in memory (fresh or stale)
1006
+ isLoading: boolean; // a loader for this path is currently running
952
1007
  };
953
1008
 
954
1009
  type CacheSnapshot = CacheSnapshotEntry[];
@@ -1019,6 +1074,8 @@ This revalidates all cached routes such as:
1019
1074
  Pattern-based invalidation is cache-only: it never sends `:param`/`[param]` to a loader.
1020
1075
  If no cached route matches, nothing is fetched.
1021
1076
 
1077
+ > Bracket syntax (`[param]`) is an **invalidation-pattern** form of `:param` — route declarations use `:param` only. Both forms are accepted here so you can copy a route pattern straight into `invalidate()`. `*` is not a valid invalidation pattern: catch-all pages are not prefetched or invalidated by path.
1078
+
1022
1079
  This also works for nested dynamic routes:
1023
1080
 
1024
1081
  ```tsx
@@ -1026,6 +1083,7 @@ await invalidate('/post/[id]/comment/:commentId');
1026
1083
  ```
1027
1084
 
1028
1085
  #### Force revalidation
1086
+
1029
1087
  By default concrete pathnames are always revalidated, even if they were never cached
1030
1088
  — this also makes `invalidate()` work on an error page with an empty cache.
1031
1089
  Pass `{ force: false }` to go back to cache-only revalidation:
@@ -1038,11 +1096,14 @@ Explicit `{ force: true }` behaves the same as the default for concrete paths. P
1038
1096
  targets stay cache-only regardless of `force`.
1039
1097
 
1040
1098
  #### Stale-only revalidation
1099
+
1041
1100
  By default, `invalidate` deletes matching cache entries and refetches them.
1042
1101
  Pass `{ staleOnly: true }` to only revalidate entries that are already stale, leaving fresh ones untouched:
1102
+
1043
1103
  ```tsx
1044
1104
  await invalidate('/notes', { staleOnly: true });
1045
1105
  ```
1106
+
1046
1107
  Note: `staleOnly` disables the default force — uncached paths are left alone, so no new
1047
1108
  network requests are started for routes you never visited.
1048
1109
 
@@ -1079,6 +1140,7 @@ will revalidate the cached child routes:
1079
1140
  /post/23
1080
1141
  /post/42/comments
1081
1142
  ```
1143
+
1082
1144
  #### Status transitions
1083
1145
 
1084
1146
  When the revalidated path matches the currently active `pathname + search`, a successful
@@ -1097,17 +1159,23 @@ cached search variant of that pathname.
1097
1159
  #### Returns
1098
1160
 
1099
1161
  An array of objects with the following structure:
1162
+
1100
1163
  ```ts
1101
- { path: string; data: unknown; error: unknown }
1164
+ {
1165
+ path: string;
1166
+ data: unknown;
1167
+ error: unknown;
1168
+ }
1102
1169
  ```
1170
+
1103
1171
  Each object represents a revalidated route, where `path` is the route pathname, `data` is the revalidated loader result, and `error` is the loader error, if any.
1104
1172
 
1105
1173
  #### Notes
1106
1174
 
1107
- * Without `force: false`, concrete pathnames you pass are always revalidated (and stored in the cache), even if they were never cached. Dynamic patterns only revalidate cached matches and never fetch the pattern itself. Pass `{ force: false }` to revalidate **only routes that already have cached data**.
1108
- * With `{ staleOnly: true }`, uncached paths are never fetched — the default force does not apply.
1109
- * Cached data is cleared before the new loader starts.
1110
- * When used as an event handler, wrap the call in an arrow function:
1175
+ - Without `force: false`, concrete pathnames you pass are always revalidated (and stored in the cache), even if they were never cached. Dynamic patterns only revalidate cached matches and never fetch the pattern itself. Pass `{ force: false }` to revalidate **only routes that already have cached data**.
1176
+ - With `{ staleOnly: true }`, uncached paths are never fetched — the default force does not apply.
1177
+ - Cached data is cleared before the new loader starts.
1178
+ - When used as an event handler, wrap the call in an arrow function:
1111
1179
 
1112
1180
  ```tsx
1113
1181
  <button onClick={() => invalidate()}>Refresh</button>
@@ -1115,7 +1183,6 @@ Each object represents a revalidated route, where `path` is the route pathname,
1115
1183
 
1116
1184
  Passing `invalidate` directly (`onClick={invalidate}`) is not supported because React passes a `MouseEvent` object to event handlers.
1117
1185
 
1118
-
1119
1186
  ### `useBlocker(callback)`
1120
1187
 
1121
1188
  Blocks navigation - including the browser's Back/Forward buttons - while `callback` returns `true`.
@@ -1123,7 +1190,7 @@ Blocks navigation - including the browser's Back/Forward buttons - while `callba
1123
1190
  The library calls `callback` on every navigation attempt with the current, target location and router context, so you can decide whether to block based on where the user is headed, not just your app's internal state:
1124
1191
 
1125
1192
  ```ts
1126
- callback: (arg: { location: Location; nextLocation: Location | null; context: Record<string, unknown> }) => boolean
1193
+ callback: (arg: { location: Location; nextLocation: Location | null; context: Record<string, unknown> }) => boolean;
1127
1194
  ```
1128
1195
 
1129
1196
  - `location` - the route the user is currently on.
@@ -1132,28 +1199,30 @@ callback: (arg: { location: Location; nextLocation: Location | null; context: Re
1132
1199
 
1133
1200
  **Returns:**
1134
1201
 
1135
- | Property | Type | Description |
1136
- |----------|------|-------------|
1137
- | `state` | `'unblocked' \| 'charged' \| 'blocked'` | `'unblocked'` — `callback` returns `false`, navigation isn't intercepted. `'charged'` — `callback` returns `true`, blocking is armed, but no navigation has been attempted yet. `'blocked'` — a navigation attempt was just intercepted; `nextLocation` inside `callback` now points to the attempted target. |
1138
- | `process()` | `() => void` | Confirm and complete the blocked navigation |
1139
- | `reset()` | `() => void` | Cancel the blocked navigation and stay on the current route |
1202
+ | Property | Type | Description |
1203
+ | ----------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1204
+ | `state` | `'unblocked' \| 'charged' \| 'blocked'` | `'unblocked'` — `callback` returns `false`, navigation isn't intercepted. `'charged'` — `callback` returns `true`, blocking is armed, but no navigation has been attempted yet. `'blocked'` — a navigation attempt was just intercepted; `nextLocation` inside `callback` now points to the attempted target. |
1205
+ | `process()` | `() => void` | Confirm and complete the blocked navigation |
1206
+ | `reset()` | `() => void` | Cancel the blocked navigation and stay on the current route |
1140
1207
 
1141
1208
  ```tsx
1142
1209
  const { state, process, reset } = useBlocker(({ nextLocation }) => hasUnsavedChanges);
1143
1210
 
1144
1211
  useEffect(() => {
1145
- if (state === 'blocked') {
1146
- // Show your custom modal
1147
- if (confirm('Leave without saving?')) {
1148
- process();
1149
- } else {
1150
- reset();
1151
- }
1152
- }
1212
+ if (state === 'blocked') {
1213
+ // Show your custom modal
1214
+ if (confirm('Leave without saving?')) {
1215
+ process();
1216
+ } else {
1217
+ reset();
1218
+ }
1219
+ }
1153
1220
  }, [state, process, reset]);
1154
1221
  ```
1155
1222
 
1156
1223
  > Works for programmatic navigation and browser Back/Forward alike — including the case where the URL already changed via Back/Forward, which the library reverts until `process()` or `reset()` is called.
1224
+ >
1225
+ > **One blocker per page.** The blocked state is global (a single store, by design): two `useBlocker` hooks on the same page do not compose — the last mounted one wins. If you need conditional blocking, decide inside one blocker callback instead of mounting several.
1157
1226
 
1158
1227
  ### Custom Blocker component
1159
1228
 
@@ -1161,19 +1230,19 @@ If you'd rather not manage the `useEffect` or conditional rendering yourself, yo
1161
1230
 
1162
1231
  ```tsx
1163
1232
  type BlockerProps = {
1164
- children: (blocker: ReturnType<typeof useBlocker>) => ReactNode;
1165
- callback: (args: BlockerCallback) => boolean;
1233
+ children: (blocker: ReturnType<typeof useBlocker>) => ReactNode;
1234
+ callback: (args: BlockerCallback) => boolean;
1166
1235
  };
1167
1236
 
1168
1237
  const Blocker = ({ callback, children }: BlockerProps) => {
1169
- const blocker = useBlocker(callback);
1170
- return blocker.state === 'blocked' ? children(blocker) : null;
1238
+ const blocker = useBlocker(callback);
1239
+ return blocker.state === 'blocked' ? children(blocker) : null;
1171
1240
  };
1172
1241
  ```
1173
1242
 
1174
1243
  ```tsx
1175
1244
  <Blocker callback={() => formState.isDirty}>
1176
- {({ process, reset }) => <Dialog onConfirm={process} onClose={reset} />}
1245
+ {({ process, reset }) => <Dialog onConfirm={process} onClose={reset} />}
1177
1246
  </Blocker>
1178
1247
  ```
1179
1248
 
@@ -1183,50 +1252,50 @@ Returns a callback that restores the saved scroll position for the current route
1183
1252
 
1184
1253
  The automatic restore covers content that is ready when navigation finishes (including route `loader` data). Call the callback yourself for content that arrives later:
1185
1254
 
1186
- * deferred data streamed via React 19 `use()`,
1187
- * lazily loaded route chunks,
1188
- * any container that mounts after the initial render.
1255
+ - deferred data streamed via React 19 `use()`,
1256
+ - lazily loaded route chunks,
1257
+ - any container that mounts after the initial render.
1189
1258
 
1190
1259
  ```tsx
1191
1260
  import { useRestoreScroll, useLoaderState } from 'clear-react-router';
1192
1261
 
1193
1262
  const SlowTable = () => {
1194
- const restoreScroll = useRestoreScroll();
1195
- const { data } = useLoaderState<{ rows: Promise<Row[]> }>();
1196
-
1197
- return (
1198
- <Suspense fallback={<Skeleton />}>
1199
- <Table rows={data.rows} onReady={restoreScroll} />
1200
- </Suspense>
1201
- );
1263
+ const restoreScroll = useRestoreScroll();
1264
+ const { data } = useLoaderState<{ rows: Promise<Row[]> }>();
1265
+
1266
+ return (
1267
+ <Suspense fallback={<Skeleton />}>
1268
+ <Table rows={data.rows} onReady={restoreScroll} />
1269
+ </Suspense>
1270
+ );
1202
1271
  };
1203
1272
  ```
1204
1273
 
1205
- Data fetched outside the route `loader` (e.g. a `useEffect` fetch inside the component) is invisible to the router, so the automatic restore can't account for it either. The rule of thumb is simple: whenever *your* data arrives and the scrollable content is in place, call the callback:
1274
+ Data fetched outside the route `loader` (e.g. a `useEffect` fetch inside the component) is invisible to the router, so the automatic restore can't account for it either. The rule of thumb is simple: whenever _your_ data arrives and the scrollable content is in place, call the callback:
1206
1275
 
1207
1276
  ```tsx
1208
1277
  const Dashboard = () => {
1209
- const restoreScroll = useRestoreScroll();
1210
- const [rows, setRows] = useState<Row[] | null>(null);
1211
-
1212
- useEffect(() => {
1213
- fetchRows().then(data => {
1214
- setRows(data);
1215
- // DOM updates after setState — wait a frame so the container exists
1216
- requestAnimationFrame(() => restoreScroll());
1217
- });
1218
- }, [restoreScroll]);
1219
-
1220
- return rows ? <Table rows={rows} /> : <Skeleton />;
1278
+ const restoreScroll = useRestoreScroll();
1279
+ const [rows, setRows] = useState<Row[] | null>(null);
1280
+
1281
+ useEffect(() => {
1282
+ fetchRows().then(data => {
1283
+ setRows(data);
1284
+ // DOM updates after setState — wait a frame so the container exists
1285
+ requestAnimationFrame(() => restoreScroll());
1286
+ });
1287
+ }, [restoreScroll]);
1288
+
1289
+ return rows ? <Table rows={rows} /> : <Skeleton />;
1221
1290
  };
1222
1291
  ```
1223
1292
 
1224
1293
  Details worth knowing:
1225
1294
 
1226
- * The callback reads the latest saved positions at call time, not at render time — so it stays correct even if called long after mount, and repeated calls pick up the newest data. It also works from components outside `<Router>` (e.g. a static navbar), since it doesn't depend on the render tree.
1227
- * Calling it is always safe: it silently does nothing when there is nothing saved for the current route, or when the route opted out with `scrollRestoration: false`.
1228
- * An optional behavior argument on the hook overrides the scroll behavior for these calls (`useRestoreScroll('smooth')`); by default the route's `scrollRestorationBehavior`, then the router's `defaultScrollRestorationBehavior`, applies.
1229
- * For element-level restoration (`scrollRestoration: ['panel']`), container `id`s must be unique and stable across visits — a typo or a remounted `id` logs a warning and skips that container.
1295
+ - The callback reads the latest saved positions at call time, not at render time — so it stays correct even if called long after mount, and repeated calls pick up the newest data. It also works from components outside `<Router>` (e.g. a static navbar), since it doesn't depend on the render tree.
1296
+ - Calling it is always safe: it silently does nothing when there is nothing saved for the current route, or when the route opted out with `scrollRestoration: false`.
1297
+ - An optional behavior argument on the hook overrides the scroll behavior for these calls (`useRestoreScroll('smooth')`); by default the route's `scrollRestorationBehavior`, then the router's `defaultScrollRestorationBehavior`, applies.
1298
+ - For element-level restoration (`scrollRestoration: ['panel']`), container `id`s must be unique and stable across visits — a typo or a remounted `id` logs a warning and skips that container.
1230
1299
 
1231
1300
  ### `useRouteStatus()`
1232
1301
 
@@ -1245,13 +1314,13 @@ To render your own loading indicator (for example next to a link while its targe
1245
1314
  import { Link, useRouteStatus } from 'clear-react-router';
1246
1315
 
1247
1316
  const NavLink = ({ to, children }: { to: string; children: ReactNode }) => {
1248
- const isLoading = useRouteStatus(status => status === 'pending' || status === 'optimistic');
1249
- return (
1250
- <Link to={to} className={({ isPending }) => (isPending ? 'link-pending' : '')}>
1251
- {children}
1252
- {isLoading && <span aria-hidden="true"> •••</span>}
1253
- </Link>
1254
- );
1317
+ const isLoading = useRouteStatus(status => status === 'pending' || status === 'optimistic');
1318
+ return (
1319
+ <Link to={to} className={({ isPending }) => (isPending ? 'link-pending' : '')}>
1320
+ {children}
1321
+ {isLoading && <span aria-hidden="true"> •••</span>}
1322
+ </Link>
1323
+ );
1255
1324
  };
1256
1325
  ```
1257
1326
 
@@ -1262,6 +1331,7 @@ For per-link pending styling without custom components, `pendingClassName` and t
1262
1331
  ### `useRouterContext()`
1263
1332
 
1264
1333
  Returns the router context object and a function to update it. Useful for accessing or modifying global state (like user authentication, theme, etc.) from anywhere in your app.
1334
+
1265
1335
  ```tsx
1266
1336
  const { setContext, context } = useRouterContext();
1267
1337
  const loginHandler = () => setContext({ ...context, user: { name: 'John' } });
@@ -1275,34 +1345,35 @@ Returns an object for working with URL query parameters. Supports reading and se
1275
1345
  import { useSearchParams } from 'clear-react-router';
1276
1346
 
1277
1347
  function ProductFilter() {
1278
- const { searchParams, getSearchParams, setSearchParams } = useSearchParams();
1348
+ const { searchParams, getSearchParams, setSearchParams } = useSearchParams();
1279
1349
 
1280
- // Get a single value or array
1281
- const brand = getSearchParams('brand'); // 'nike' | ['nike', 'reebok'] | ''
1350
+ // Get a single value or array
1351
+ const brand = getSearchParams('brand'); // 'nike' | ['nike', 'reebok'] | ''
1282
1352
 
1283
- // Set a single value
1284
- setSearchParams('brand', 'nike'); // ?brand=nike
1353
+ // Set a single value
1354
+ setSearchParams('brand', 'nike'); // ?brand=nike
1285
1355
 
1286
- // Set multiple values (array)
1287
- setSearchParams('brand', ['nike', 'reebok']); // ?brand=nike&brand=reebok
1356
+ // Set multiple values (array)
1357
+ setSearchParams('brand', ['nike', 'reebok']); // ?brand=nike&brand=reebok
1288
1358
 
1289
- // Functional update (preserves other params)
1290
- setSearchParams((prev) => {
1291
- prev.set('page', '2');
1292
- prev.append('color', 'red');
1293
- return prev;
1294
- });
1359
+ // Functional update (preserves other params)
1360
+ setSearchParams(prev => {
1361
+ prev.set('page', '2');
1362
+ prev.append('color', 'red');
1363
+ return prev;
1364
+ });
1295
1365
 
1296
- // Direct access to URLSearchParams
1297
- const allParams = searchParams.toString(); // "brand=nike&brand=reebok&page=2"
1366
+ // Direct access to URLSearchParams
1367
+ const allParams = searchParams.toString(); // "brand=nike&brand=reebok&page=2"
1298
1368
  }
1299
1369
  ```
1370
+
1300
1371
  **Returns:**
1301
1372
 
1302
- | Property | Type | Description |
1303
- |----------|------|-------------|
1304
- | `searchParams` | `URLSearchParams` | Raw `URLSearchParams` object for low-level access |
1305
- | `getSearchParams` | `(key: string) => string \| string[]` | Returns a single value or an array if multiple values exist for the key |
1373
+ | Property | Type | Description |
1374
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
1375
+ | `searchParams` | `URLSearchParams` | Raw `URLSearchParams` object for low-level access |
1376
+ | `getSearchParams` | `(key: string) => string \| string[]` | Returns a single value or an array if multiple values exist for the key |
1306
1377
  | `setSearchParams` | `(param: string, value: string \| string[]) => void` `or` `(updater: (prev: URLSearchParams) => URLSearchParams) => void` | Update query parameters. Supports single values, arrays, or functional updates |
1307
1378
 
1308
1379
  **Key features:**
@@ -1317,23 +1388,23 @@ function ProductFilter() {
1317
1388
 
1318
1389
  ```tsx
1319
1390
  function ProductFilter() {
1320
- const { searchParams, setSearchParams } = useSearchParams();
1321
- const { pathname } = useLocation();
1322
- const navigate = useNavigate();
1323
- const invalidate = useInvalidate();
1324
-
1325
- // Full navigation: runs beforeLoad / loader / afterLoad and pushes a history entry
1326
- const applyFilter = () => {
1327
- const next = new URLSearchParams(searchParams);
1328
- next.set('brand', 'nike');
1329
- navigate({ pathname, search: `?${next.toString()}` });
1330
- };
1331
-
1332
- // Explicit revalidation: keeps the history entry, reruns the loader, skips beforeLoad / afterLoad
1333
- const revalidateFilter = async () => {
1334
- setSearchParams('brand', 'nike');
1335
- await invalidate();
1336
- };
1391
+ const { searchParams, setSearchParams } = useSearchParams();
1392
+ const { pathname } = useLocation();
1393
+ const navigate = useNavigate();
1394
+ const invalidate = useInvalidate();
1395
+
1396
+ // Full navigation: runs beforeLoad / loader / afterLoad and pushes a history entry
1397
+ const applyFilter = () => {
1398
+ const next = new URLSearchParams(searchParams);
1399
+ next.set('brand', 'nike');
1400
+ navigate({ pathname, search: `?${next.toString()}` });
1401
+ };
1402
+
1403
+ // Explicit revalidation: keeps the history entry, reruns the loader, skips beforeLoad / afterLoad
1404
+ const revalidateFilter = async () => {
1405
+ setSearchParams('brand', 'nike');
1406
+ await invalidate();
1407
+ };
1337
1408
  }
1338
1409
  ```
1339
1410
 
@@ -1342,6 +1413,7 @@ function ProductFilter() {
1342
1413
  ## Lazy Loading
1343
1414
 
1344
1415
  Clear Router supports code-splitting out of the box. Simply wrap dynamic import into a library's `lazy` function:
1416
+
1345
1417
  ```tsx
1346
1418
  import { lazy } from 'clear-react-router';
1347
1419
 
@@ -1371,14 +1443,14 @@ fast data while slow data streams in separately:
1371
1443
 
1372
1444
  ```tsx
1373
1445
  const Slow = () => {
1374
- const { data } = useLoaderState<{ slow: Promise<string> }>();
1375
- return use(data.slow);
1446
+ const { data } = useLoaderState<{ slow: Promise<string> }>();
1447
+ return use(data.slow);
1376
1448
  };
1377
1449
 
1378
1450
  const About = () => (
1379
- <Suspense fallback={<Skeleton />}>
1380
- <Slow />
1381
- </Suspense>
1451
+ <Suspense fallback={<Skeleton />}>
1452
+ <Slow />
1453
+ </Suspense>
1382
1454
  );
1383
1455
  ```
1384
1456
 
@@ -1407,6 +1479,7 @@ View Transitions API requires modern browsers:
1407
1479
  For older browsers, the router gracefully falls back to regular navigation without animation.
1408
1480
 
1409
1481
  ## Requirements
1482
+
1410
1483
  - React 16.8+ (for React.lazy and Suspense)
1411
1484
  - Use `default` export for your lazy-loaded components
1412
1485
 
@@ -1421,5 +1494,6 @@ LRU eviction with a tiny cache, gcTime cleanup, an invalidation lab, a live cach
1421
1494
  in-browser server.
1422
1495
  Open devtools and click around.
1423
1496
 
1424
- ## License
1425
- MIT
1497
+ ## License
1498
+
1499
+ MIT