clear-react-router 2.5.5 → 2.5.7
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 +472 -401
- package/dist/components/Link.d.ts +3 -3
- package/dist/components/Router.d.ts +1 -1
- package/dist/config/routerConfig.d.ts +1 -0
- package/dist/index.js +101 -41
- package/dist/types.d.ts +10 -0
- package/dist/utils/utils.d.ts +8 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -13,11 +13,11 @@ 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
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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
|
|
|
@@ -25,11 +25,10 @@ It provides first-class support for:
|
|
|
25
25
|
> [Clear Safe Router](https://github.com/AndrewBubnov/clear-safe-router) ([npm](https://www.npmjs.com/package/clear-safe-router)) —
|
|
26
26
|
> built on this runtime.
|
|
27
27
|
|
|
28
|
-
|
|
29
28
|
## Features
|
|
30
29
|
|
|
31
30
|
- **Nested Routes** - Organize your UI with nested layouts and routes
|
|
32
|
-
- **Route Layouts** - A `layout` declared on a route wraps it
|
|
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
|
|
33
32
|
- **Data Loading** - Built-in loaders with TTL-based caching (`staleTime`)
|
|
34
33
|
- **Navigation Blocking** - Prevent accidental navigation with `useBlocker`
|
|
35
34
|
- **Smooth Animations** - Page transitions with fade effect (customizable duration)
|
|
@@ -38,7 +37,7 @@ It provides first-class support for:
|
|
|
38
37
|
- **Cache invalidation** - Manual route invalidation
|
|
39
38
|
- **Bounded Cache** - Automatically evicts least recently used entries once `maxCacheSize` is reached, keeping memory usage predictable in long sessions
|
|
40
39
|
- **Cache inspection** - Opt into a live, read-only snapshot of cached loader entries with `enableCacheSnapshot` and `useCacheSnapshot()`
|
|
41
|
-
- **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
|
|
42
41
|
- **Lazy Loading** - Code-split your routes with dynamic imports for optimal performance
|
|
43
42
|
- **Scroll Restoration** — Automatically saves and restores scroll position when navigating back to a page (preserves user's scroll position)
|
|
44
43
|
- **Optimistic navigation** — Instantly renders stale cached data while fresh data is loaded in the background.
|
|
@@ -68,27 +67,28 @@ The host rewrite only serves the app shell. To render your own UI for unknown cl
|
|
|
68
67
|
|
|
69
68
|
### `Router`
|
|
70
69
|
|
|
71
|
-
| Prop
|
|
72
|
-
|
|
73
|
-
| `routes`
|
|
74
|
-
| `maxCacheSize`
|
|
75
|
-
| `isAnimated`
|
|
76
|
-
| `animationDuration`
|
|
77
|
-
| `context`
|
|
78
|
-
| `errorBoundary`
|
|
79
|
-
| `defaultMinLoaderDuration`
|
|
80
|
-
| `defaultLoaderFallback`
|
|
81
|
-
| `defaultErrorElement`
|
|
82
|
-
| `defaultRetry`
|
|
83
|
-
| `defaultStaleTime`
|
|
84
|
-
| `
|
|
85
|
-
| `
|
|
86
|
-
| `
|
|
87
|
-
| `
|
|
88
|
-
| `
|
|
89
|
-
| `
|
|
90
|
-
| `
|
|
91
|
-
| `
|
|
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 |
|
|
92
92
|
|
|
93
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.
|
|
94
94
|
|
|
@@ -98,59 +98,109 @@ Required: `<Router>` expects the output of `createRouter` (`RouteItem[]` with bu
|
|
|
98
98
|
|
|
99
99
|
Normalizes route configuration. Extracts dynamic params, builds nested paths.
|
|
100
100
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
|
108
|
-
|
|
|
109
|
-
| `
|
|
110
|
-
| `
|
|
111
|
-
| `
|
|
112
|
-
| `
|
|
113
|
-
| `
|
|
114
|
-
| `
|
|
115
|
-
| `
|
|
116
|
-
| `
|
|
117
|
-
| `
|
|
118
|
-
| `
|
|
119
|
-
| `
|
|
120
|
-
| `
|
|
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 |
|
|
121
128
|
|
|
122
129
|
`beforeLoad`, `loader` and `actions` receive:
|
|
123
130
|
|
|
124
131
|
```ts
|
|
125
132
|
{
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
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
|
|
131
138
|
}
|
|
132
139
|
```
|
|
140
|
+
|
|
133
141
|
see [`Location`](#uselocation) and [`Where you came from`](#where-you-came-from) for type details
|
|
134
|
-
|
|
142
|
+
|
|
135
143
|
`beforeLoad` additionally receives:
|
|
144
|
+
|
|
136
145
|
```ts
|
|
137
146
|
{
|
|
138
|
-
|
|
147
|
+
redirect: (arg: Location | string) => Promise<void>; // Programmatic redirection, see [redirect](#redirect)
|
|
139
148
|
}
|
|
140
149
|
```
|
|
150
|
+
|
|
141
151
|
see [`redirect`](#redirect) for details on programmatic redirects
|
|
142
152
|
|
|
143
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.
|
|
144
154
|
|
|
145
155
|
`loader` additionally receives:
|
|
156
|
+
|
|
146
157
|
```ts
|
|
147
158
|
{
|
|
148
|
-
|
|
149
|
-
|
|
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
|
|
150
161
|
}
|
|
151
162
|
```
|
|
163
|
+
|
|
152
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.
|
|
153
|
-
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.
|
|
154
204
|
|
|
155
205
|
### Nested routes
|
|
156
206
|
|
|
@@ -158,14 +208,14 @@ A child `path` is **appended to the parent pattern**. Write only the new segment
|
|
|
158
208
|
|
|
159
209
|
```tsx
|
|
160
210
|
const routes = createRouter([
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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
|
+
},
|
|
169
219
|
]);
|
|
170
220
|
```
|
|
171
221
|
|
|
@@ -187,9 +237,9 @@ Add one route with `path: '*'` as the **last** entry. It matches any depth:
|
|
|
187
237
|
|
|
188
238
|
```tsx
|
|
189
239
|
const routes = createRouter([
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
240
|
+
{ path: '/', element: <Home /> },
|
|
241
|
+
// ...other routes
|
|
242
|
+
{ path: '*', element: <NotFound /> },
|
|
193
243
|
]);
|
|
194
244
|
```
|
|
195
245
|
|
|
@@ -197,40 +247,40 @@ const routes = createRouter([
|
|
|
197
247
|
|
|
198
248
|
### Layouts
|
|
199
249
|
|
|
200
|
-
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
|
|
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.
|
|
201
251
|
|
|
202
252
|
```tsx
|
|
203
253
|
const AppShell = ({ children }: { children: ReactNode }) => (
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
254
|
+
<div className="shell">
|
|
255
|
+
<TopNav />
|
|
256
|
+
{children}
|
|
257
|
+
</div>
|
|
208
258
|
);
|
|
209
259
|
|
|
210
260
|
const SectionLayout = ({ children }: { children: ReactNode }) => (
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
261
|
+
<div className="section">
|
|
262
|
+
<SectionNav />
|
|
263
|
+
{children}
|
|
264
|
+
</div>
|
|
215
265
|
);
|
|
216
266
|
|
|
217
267
|
const routes = createRouter([
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
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
|
+
},
|
|
234
284
|
]);
|
|
235
285
|
```
|
|
236
286
|
|
|
@@ -253,30 +303,31 @@ Rule of thumb: `to` for plain URLs, `path` + `params` when you want the pattern
|
|
|
253
303
|
|
|
254
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.
|
|
255
305
|
|
|
256
|
-
| Prop
|
|
257
|
-
|
|
258
|
-
| `to`
|
|
259
|
-
| `path`
|
|
260
|
-
| `params`
|
|
261
|
-
| `search`
|
|
262
|
-
| `state`
|
|
263
|
-
| `as`
|
|
264
|
-
| `exact`
|
|
265
|
-
| `prefetch`
|
|
266
|
-
| `hoverPrefetchDelay` | `number`
|
|
267
|
-
| `
|
|
268
|
-
| `
|
|
269
|
-
| `
|
|
270
|
-
| `
|
|
271
|
-
| `
|
|
272
|
-
| `
|
|
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
|
+
| `onMouseEnter` / `onMouseLeave` | Mouse event handlers | `undefined` | Called on hover (e.g. to animate icons). Your handlers run first — the built-in `hover` prefetch still fires afterwards: the handlers are merged, not overridden |
|
|
318
|
+
| `children` | `ReactNode` | required | Content to render inside the link |
|
|
319
|
+
| `className` | `string \| ({ isActive, isPending }) => string` | `undefined` | CSS class name(s). Can be a function for dynamic styling |
|
|
320
|
+
| `style` | `CSSProperties \| ({ isActive, isPending }) => CSSProperties` | `undefined` | Inline styles. Can be a function for dynamic styling |
|
|
321
|
+
| `activeClassName` | `string` optional | `'active-link'` | Class name applied when the link matches the current URL |
|
|
322
|
+
| `pendingClassName` | `string` optional | `'pending-link'` | Class name applied when the link's target is loading |
|
|
323
|
+
| `beforeNavigate` | `() => Promise<void> \| undefined` | `undefined` | Callback fired before navigation |
|
|
273
324
|
|
|
274
325
|
**State values:**
|
|
275
326
|
|
|
276
|
-
| State
|
|
277
|
-
|
|
278
|
-
| `isActive`
|
|
279
|
-
| `isPending` | `boolean` | `true` when the target route is currently loading (loader is running)
|
|
327
|
+
| State | Type | Description |
|
|
328
|
+
| ----------- | --------- | ----------------------------------------------------------------------------- |
|
|
329
|
+
| `isActive` | `boolean` | `true` when the link's `to` matches the current URL considering `exact` value |
|
|
330
|
+
| `isPending` | `boolean` | `true` when the target route is currently loading (loader is running) |
|
|
280
331
|
|
|
281
332
|
### Accessibility
|
|
282
333
|
|
|
@@ -286,7 +337,7 @@ Extra `data-*` and `aria-*` props passed to `<Link>` (e.g. `data-testid`, `aria-
|
|
|
286
337
|
|
|
287
338
|
```tsx
|
|
288
339
|
<Link to="/about" aria-label="About section" data-testid="about-link">
|
|
289
|
-
|
|
340
|
+
About
|
|
290
341
|
</Link>
|
|
291
342
|
```
|
|
292
343
|
|
|
@@ -294,14 +345,14 @@ When using a custom element via `as`, these attributes arrive in `props` togethe
|
|
|
294
345
|
|
|
295
346
|
### Prefetch Strategies
|
|
296
347
|
|
|
297
|
-
| Strategy
|
|
298
|
-
|
|
299
|
-
| `'hover'`
|
|
300
|
-
| `'render'`
|
|
348
|
+
| Strategy | Behavior |
|
|
349
|
+
| ------------ | -------------------------------------------------------------------------- |
|
|
350
|
+
| `'hover'` | Prefetches when the user hovers over the link (with configurable delay) |
|
|
351
|
+
| `'render'` | Prefetches immediately when the link is rendered |
|
|
301
352
|
| `'viewport'` | Prefetches when the link enters the viewport (using Intersection Observer) |
|
|
302
|
-
| `'none'`
|
|
353
|
+
| `'none'` | No prefetching |
|
|
303
354
|
|
|
304
|
-
> A prefetched entry is considered fresh for 30 seconds. The first navigation within
|
|
355
|
+
> 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.
|
|
305
356
|
|
|
306
357
|
### Custom elements via `as`
|
|
307
358
|
|
|
@@ -314,23 +365,19 @@ When using `as` to render a custom component instead of the default `<a>`, your
|
|
|
314
365
|
|
|
315
366
|
```tsx
|
|
316
367
|
// ✅ correct — every prop is forwarded to the host element
|
|
317
|
-
const Button = ({ children, ...props }: ElementProps<HTMLButtonElement>) =>
|
|
318
|
-
<button {...props}>{children}</button>
|
|
319
|
-
);
|
|
368
|
+
const Button = ({ children, ...props }: ElementProps<HTMLButtonElement>) => <button {...props}>{children}</button>;
|
|
320
369
|
|
|
321
370
|
// ❌ wrong — ref, event handlers, and href are silently dropped
|
|
322
|
-
const Button = ({ children }: { children: ReactNode }) =>
|
|
323
|
-
<button>{children}</button>
|
|
324
|
-
);
|
|
371
|
+
const Button = ({ children }: { children: ReactNode }) => <button>{children}</button>;
|
|
325
372
|
```
|
|
326
373
|
|
|
327
374
|
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:
|
|
328
375
|
|
|
329
376
|
```tsx
|
|
330
377
|
const Button = ({ children, ...props }: ElementProps<HTMLButtonElement>) => (
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
378
|
+
<button {...props} className={`btn ${props.className ?? ''}`}>
|
|
379
|
+
{children}
|
|
380
|
+
</button>
|
|
334
381
|
);
|
|
335
382
|
```
|
|
336
383
|
|
|
@@ -364,6 +411,7 @@ import { Button } from '@mui/material';
|
|
|
364
411
|
To about page
|
|
365
412
|
</Link>
|
|
366
413
|
```
|
|
414
|
+
|
|
367
415
|
### Styling link states with CSS
|
|
368
416
|
|
|
369
417
|
Before reaching for `as`, check whether CSS is enough: active and loading states are already
|
|
@@ -374,25 +422,25 @@ screen readers) intact:
|
|
|
374
422
|
|
|
375
423
|
```tsx
|
|
376
424
|
<Link to="/playground/settings" aria-label="Settings" className="gear-link">
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
425
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true">
|
|
426
|
+
<path d="..." />
|
|
427
|
+
</svg>
|
|
380
428
|
</Link>
|
|
381
429
|
```
|
|
382
430
|
|
|
383
431
|
```css
|
|
384
432
|
/* Active page — no state plumbing needed */
|
|
385
433
|
.gear-link[aria-current='page'] {
|
|
386
|
-
|
|
434
|
+
color: steelblue;
|
|
387
435
|
}
|
|
388
436
|
/* CSS beats SVG presentation attributes (fill="none"), so this fills the icon: */
|
|
389
437
|
.gear-link[aria-current='page'] svg {
|
|
390
|
-
|
|
391
|
-
|
|
438
|
+
fill: steelblue;
|
|
439
|
+
stroke: steelblue;
|
|
392
440
|
}
|
|
393
441
|
/* Target is loading: */
|
|
394
442
|
.gear-link[aria-busy='true'] {
|
|
395
|
-
|
|
443
|
+
opacity: 0.6;
|
|
396
444
|
}
|
|
397
445
|
```
|
|
398
446
|
|
|
@@ -445,6 +493,7 @@ Reach for `as` only when the element itself must change (a `<button>`, a UI-kit
|
|
|
445
493
|
Settings
|
|
446
494
|
</Link>
|
|
447
495
|
```
|
|
496
|
+
|
|
448
497
|
**Important**: prefetch="render" should be used sparingly, as it preloads data immediately when the link is rendered, which may cause unnecessary network requests.
|
|
449
498
|
|
|
450
499
|
## Retry
|
|
@@ -498,10 +547,10 @@ Unlike many routing libraries, retry is **not limited to the initial loader exec
|
|
|
498
547
|
|
|
499
548
|
The retry policy is applied to the router's **cache revalidation mechanism**, so it automatically works for every operation that reloads route data, including:
|
|
500
549
|
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
550
|
+
- Initial route loading
|
|
551
|
+
- Cache revalidation
|
|
552
|
+
- `invalidate()`
|
|
553
|
+
- `prefetch()`
|
|
505
554
|
|
|
506
555
|
This ensures consistent behavior regardless of how the data is being refreshed.
|
|
507
556
|
|
|
@@ -519,40 +568,39 @@ Function provided to `beforeLoad` for programmatic redirection.
|
|
|
519
568
|
import type { createRouter } from 'clear-react-router';
|
|
520
569
|
|
|
521
570
|
const routes = createRouter([
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
571
|
+
{
|
|
572
|
+
path: '/dashboard',
|
|
573
|
+
element: <Dashboard />,
|
|
574
|
+
beforeLoad: ({ context, redirect }) => {
|
|
575
|
+
if (!context.isAuthorized) return redirect('/');
|
|
576
|
+
},
|
|
577
|
+
},
|
|
529
578
|
]);
|
|
530
579
|
|
|
531
580
|
const routes = createRouter([
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
581
|
+
{
|
|
582
|
+
path: '/dashboard',
|
|
583
|
+
element: <Dashboard />,
|
|
584
|
+
beforeLoad: ({ context, redirect }) => {
|
|
585
|
+
if (!context.isAuthorized) return redirect({ pathname: '/login', state: { from: '/dashboard' } });
|
|
586
|
+
},
|
|
587
|
+
},
|
|
539
588
|
]);
|
|
540
589
|
|
|
541
590
|
const routes = createRouter([
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
591
|
+
{
|
|
592
|
+
path: '/user/:userId',
|
|
593
|
+
loader: async ({ params, context, setContext }) => {
|
|
594
|
+
const user = await fetchUser(params.userId);
|
|
595
|
+
setContext({ ...context, currentUser: user });
|
|
596
|
+
return { user };
|
|
597
|
+
},
|
|
598
|
+
beforeLoad: async ({ context, setContext, redirect }) => {
|
|
599
|
+
if (!context.token) return redirect('/login');
|
|
600
|
+
setContext({ ...context, lastVisit: Date.now() });
|
|
601
|
+
},
|
|
602
|
+
},
|
|
554
603
|
]);
|
|
555
|
-
|
|
556
604
|
```
|
|
557
605
|
|
|
558
606
|
### Usage with Parameters
|
|
@@ -563,29 +611,29 @@ The `loader`, `beforeLoad`, and `afterLoad` hooks receive `params` (extracted fr
|
|
|
563
611
|
import type { createRouter } from 'clear-react-router';
|
|
564
612
|
|
|
565
613
|
const routes = createRouter([
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
614
|
+
{
|
|
615
|
+
path: '/user/:userId',
|
|
616
|
+
element: <UserProfile />,
|
|
617
|
+
loader: async ({ params, context }) => {
|
|
618
|
+
// params.userId is available from the URL
|
|
619
|
+
const user = await fetchUser(params.userId);
|
|
620
|
+
return { user };
|
|
621
|
+
},
|
|
622
|
+
beforeLoad: async ({ params, context, redirect }) => {
|
|
623
|
+
// Authentication check
|
|
624
|
+
if (!context.isAuthorized) {
|
|
625
|
+
return redirect('/login');
|
|
626
|
+
}
|
|
627
|
+
// Validate parameter
|
|
628
|
+
if (!params.userId || !isValidUserId(params.userId)) {
|
|
629
|
+
return redirect('/users');
|
|
630
|
+
}
|
|
631
|
+
},
|
|
632
|
+
afterLoad: ({ params, context }) => {
|
|
633
|
+
// Analytics or side effects
|
|
634
|
+
console.log(`User ${params.userId} loaded`);
|
|
635
|
+
},
|
|
636
|
+
},
|
|
589
637
|
]);
|
|
590
638
|
```
|
|
591
639
|
|
|
@@ -606,11 +654,11 @@ actions?: ({ params, context, searchParams, setContext, location }) => ({
|
|
|
606
654
|
|
|
607
655
|
```ts
|
|
608
656
|
{
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
657
|
+
params: Record<string, string>; // Route parameters
|
|
658
|
+
context: Record<string, unknown>; // Router context
|
|
659
|
+
setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
|
|
660
|
+
searchParams: Record<string, string>; // URL search parameters
|
|
661
|
+
location: Location; // Route location
|
|
614
662
|
}
|
|
615
663
|
```
|
|
616
664
|
|
|
@@ -626,15 +674,15 @@ A record where each key is an action name and each value is a function accepting
|
|
|
626
674
|
import { useSubmitAction } from 'clear-react-router';
|
|
627
675
|
|
|
628
676
|
const CreateUserForm = () => {
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
677
|
+
const { onSubmit, isSubmitting, error } = useSubmitAction('createUser');
|
|
678
|
+
|
|
679
|
+
return (
|
|
680
|
+
<form onSubmit={onSubmit}>
|
|
681
|
+
<input name="email" disabled={isSubmitting} />
|
|
682
|
+
<button disabled={isSubmitting}>Create</button>
|
|
683
|
+
{error && <span>{error.message}</span>}
|
|
684
|
+
</form>
|
|
685
|
+
);
|
|
638
686
|
};
|
|
639
687
|
```
|
|
640
688
|
|
|
@@ -647,28 +695,28 @@ const { register, handleSubmit } = useForm<FormValues>();
|
|
|
647
695
|
const { submit, isSubmitting } = useSubmitAction('createUser');
|
|
648
696
|
|
|
649
697
|
<form onSubmit={handleSubmit(submit)}>
|
|
650
|
-
|
|
651
|
-
</form
|
|
698
|
+
<input {...register('email')} disabled={isSubmitting} />
|
|
699
|
+
</form>;
|
|
652
700
|
```
|
|
653
701
|
|
|
654
702
|
Arguments:
|
|
655
703
|
|
|
656
|
-
| Argument
|
|
657
|
-
|
|
658
|
-
| `action`
|
|
659
|
-
| `options.onSuccess` | `(data: unknown) => void \| undefined`
|
|
660
|
-
| `options.onError`
|
|
661
|
-
| `options.autoReset` | `boolean \| undefined`
|
|
704
|
+
| Argument | Type | Default | Description |
|
|
705
|
+
| ------------------- | --------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------- |
|
|
706
|
+
| `action` | `string` | — | The action key defined in the route's `actions` |
|
|
707
|
+
| `options.onSuccess` | `(data: unknown) => void \| undefined` | `undefined` | Called after a successful submission |
|
|
708
|
+
| `options.onError` | `(error: unknown) => void \| undefined` | `undefined` | Called if the action throws |
|
|
709
|
+
| `options.autoReset` | `boolean \| undefined` | `true` | Reset the form element after a successful native submission (`onSubmit` only — has no effect on `submit`) |
|
|
662
710
|
|
|
663
711
|
Return value:
|
|
664
712
|
|
|
665
|
-
| Field
|
|
666
|
-
|
|
667
|
-
| `submit`
|
|
668
|
-
| `onSubmit`
|
|
669
|
-
| `data`
|
|
670
|
-
| `error`
|
|
671
|
-
| `isSubmitting` | `boolean`
|
|
713
|
+
| Field | Type | Description |
|
|
714
|
+
| -------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------- |
|
|
715
|
+
| `submit` | `(data: Record<string, unknown>) => Promise<{ data: unknown; error: Error \| null }>` | Runs the action directly, from any form data source |
|
|
716
|
+
| `onSubmit` | `(evt: SubmitEvent<HTMLFormElement>) => Promise<void>` | Ready-made handler for a native `<form onSubmit={...}>` |
|
|
717
|
+
| `data` | `unknown` | Result of the last successful submission |
|
|
718
|
+
| `error` | `Error \| null` | Error from the last failed submission |
|
|
719
|
+
| `isSubmitting` | `boolean` | `true` while the action is in flight |
|
|
672
720
|
|
|
673
721
|
> The native `onSubmit` handler converts the form via `Object.fromEntries(new FormData(...))` —
|
|
674
722
|
> if your form has multiple fields sharing the same `name` (checkbox groups, `<select multiple>`),
|
|
@@ -681,10 +729,10 @@ Return value:
|
|
|
681
729
|
|
|
682
730
|
### Arguments
|
|
683
731
|
|
|
684
|
-
| Argument
|
|
685
|
-
|
|
686
|
-
| `action`
|
|
687
|
-
| `options` | `Options` | Optional callbacks invoked after the action succeeds or fails.
|
|
732
|
+
| Argument | Type | Description |
|
|
733
|
+
| --------- | --------- | -------------------------------------------------------------------------------------------------------- |
|
|
734
|
+
| `action` | `string` | Name of the route action to execute. Must match a key returned from the route's `actions` configuration. |
|
|
735
|
+
| `options` | `Options` | Optional callbacks invoked after the action succeeds or fails. |
|
|
688
736
|
|
|
689
737
|
```ts
|
|
690
738
|
type Options = { onSuccess?: (args: unknown) => void; onError?: (args: unknown) => void };
|
|
@@ -694,14 +742,13 @@ type Options = { onSuccess?: (args: unknown) => void; onError?: (args: unknown)
|
|
|
694
742
|
const save = useAction('save');
|
|
695
743
|
const handleClick = async () => await save({ data: 'Hello world!' });
|
|
696
744
|
|
|
697
|
-
<button onClick={handleClick}>Save</button
|
|
745
|
+
<button onClick={handleClick}>Save</button>;
|
|
698
746
|
```
|
|
699
747
|
|
|
700
748
|
`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.
|
|
701
749
|
|
|
702
750
|
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.
|
|
703
751
|
|
|
704
|
-
|
|
705
752
|
### Error Boundaries
|
|
706
753
|
|
|
707
754
|
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.
|
|
@@ -711,8 +758,9 @@ import { Router } from 'clear-react-router';
|
|
|
711
758
|
import { routes } from './routes';
|
|
712
759
|
import { ErrorBoundary } from './components/ErrorBoundary';
|
|
713
760
|
|
|
714
|
-
const App = () => <Router routes={routes} errorBoundary={ErrorBoundary}
|
|
761
|
+
const App = () => <Router routes={routes} errorBoundary={ErrorBoundary} />;
|
|
715
762
|
```
|
|
763
|
+
|
|
716
764
|
**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.
|
|
717
765
|
|
|
718
766
|
## Hooks
|
|
@@ -722,13 +770,17 @@ const App = () => <Router routes={routes} errorBoundary={ErrorBoundary} />
|
|
|
722
770
|
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.
|
|
723
771
|
|
|
724
772
|
```tsx
|
|
725
|
-
type NavigationLocation = {
|
|
773
|
+
type NavigationLocation = {
|
|
774
|
+
pathname: string;
|
|
775
|
+
search?: string | Record<string, string | number | boolean | null | undefined>;
|
|
776
|
+
state?: unknown;
|
|
777
|
+
};
|
|
726
778
|
|
|
727
779
|
const navigate = useNavigate();
|
|
728
780
|
|
|
729
|
-
navigate('/about');
|
|
730
|
-
navigate({ pathname: '/user/123', search: { user: 'Jane Doe' }, state: { from: 'home' } });
|
|
731
|
-
navigate(-1);
|
|
781
|
+
navigate('/about'); // string
|
|
782
|
+
navigate({ pathname: '/user/123', search: { user: 'Jane Doe' }, state: { from: 'home' } }); // NavigationLocation
|
|
783
|
+
navigate(-1); // go back
|
|
732
784
|
```
|
|
733
785
|
|
|
734
786
|
**Note:** Navigation state can be accessed via [`useLocation()`](#uselocation):
|
|
@@ -765,7 +817,7 @@ navigation, pass a route pattern via `path` with matching `params` instead — t
|
|
|
765
817
|
interpolates the segments (values are URL-encoded, a missing param throws):
|
|
766
818
|
|
|
767
819
|
```tsx
|
|
768
|
-
<Link path="/product/:productId" params={{ productId: '7' }}
|
|
820
|
+
<Link path="/product/:productId" params={{ productId: '7' }} />;
|
|
769
821
|
navigate({ path: '/product/:productId', params: { productId: '7' } });
|
|
770
822
|
```
|
|
771
823
|
|
|
@@ -776,7 +828,7 @@ Declarative and imperative forms are equivalent — this link:
|
|
|
776
828
|
|
|
777
829
|
```tsx
|
|
778
830
|
<Link path="/nest/:nestId/item/:itemId" params={{ nestId, itemId }}>
|
|
779
|
-
|
|
831
|
+
{itemId}
|
|
780
832
|
</Link>
|
|
781
833
|
```
|
|
782
834
|
|
|
@@ -785,9 +837,7 @@ does the same as this button:
|
|
|
785
837
|
```tsx
|
|
786
838
|
const navigate = useNavigate();
|
|
787
839
|
|
|
788
|
-
<button onClick={() => navigate({ path: '/nest/:nestId/item/:itemId', params: { nestId, itemId } })}>
|
|
789
|
-
{itemId}
|
|
790
|
-
</button>
|
|
840
|
+
<button onClick={() => navigate({ path: '/nest/:nestId/item/:itemId', params: { nestId, itemId } })}>{itemId}</button>;
|
|
791
841
|
```
|
|
792
842
|
|
|
793
843
|
Same type-checking, same interpolation. Use links for navigation, buttons with `navigate`
|
|
@@ -802,37 +852,38 @@ userland pattern — adopt it ladder-style, each rung optional:
|
|
|
802
852
|
- **Rung 1 — `path` + `params` on plain `Link`.** No union, no wrapper, no setup:
|
|
803
853
|
TypeScript infers the pattern from the `path` literal itself and checks `params`
|
|
804
854
|
against it:
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
855
|
+
```tsx
|
|
856
|
+
<Link path="/product/:productId" params={{ productId: '7' }} /> // ok
|
|
857
|
+
<Link path="/product/:productId" /> // error: params missing
|
|
858
|
+
<Link path="/product/:productId" params={{ id: '7' }} /> // error: wrong param name
|
|
859
|
+
```
|
|
860
|
+
But path _existence_ is unchecked — there is no list to check against, so this
|
|
861
|
+
compiles silently:
|
|
862
|
+
```tsx
|
|
863
|
+
<Link path="/playgroud/cache" /> // typo, no error (no union knows the routes)
|
|
864
|
+
```
|
|
865
|
+
In other words: rung 1 checks internal consistency (`path` ↔ `params`), not the
|
|
866
|
+
outside world (path ↔ app routes). That half needs a union — rung 3.
|
|
817
867
|
- **Rung 2 — thin wrapper, no union.** Gives the pattern a name without any type file:
|
|
818
|
-
```tsx
|
|
819
|
-
import { Link, type LinkProps } from 'clear-react-router';
|
|
820
868
|
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
869
|
+
```tsx
|
|
870
|
+
import { Link, type LinkProps } from 'clear-react-router';
|
|
871
|
+
|
|
872
|
+
export const AppLink = <T extends HTMLElement = HTMLAnchorElement>(props: LinkProps<T>) => <Link {...props} />;
|
|
873
|
+
```
|
|
874
|
+
|
|
825
875
|
- **Rung 3 — wrapper + union.** Binds one union for existence checking:
|
|
826
|
-
```tsx
|
|
827
|
-
type AppPaths = '/cache' | '/product/:productId';
|
|
828
876
|
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
877
|
+
```tsx
|
|
878
|
+
type AppPaths = '/cache' | '/product/:productId';
|
|
879
|
+
|
|
880
|
+
export const AppLink = <T extends HTMLElement = HTMLAnchorElement>(props: LinkProps<T, AppPaths>) => (
|
|
881
|
+
<Link {...props} />
|
|
882
|
+
);
|
|
832
883
|
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
884
|
+
<AppLink path="/product/:productId" params={{ productId: '7' }} /> // ok
|
|
885
|
+
<AppLink path="/playgroud/cache" /> // error: not in AppPaths
|
|
886
|
+
```
|
|
836
887
|
|
|
837
888
|
The union is generated by script or hand-written.
|
|
838
889
|
Keep it next to the routes so drift is visible in review; a forgotten path fails
|
|
@@ -841,16 +892,18 @@ compilation at usage (fail-closed), a leftover entry is harmless.
|
|
|
841
892
|
### `useLocation()`
|
|
842
893
|
|
|
843
894
|
Returns current location `{ pathname, search, state }`.
|
|
895
|
+
|
|
844
896
|
```tsx
|
|
845
897
|
type Location = {
|
|
846
898
|
pathname: string;
|
|
847
899
|
search?: string;
|
|
848
900
|
state?: unknown;
|
|
849
901
|
prevLocation?: Omit<Location, 'state' | 'prevLocation'>;
|
|
850
|
-
}
|
|
902
|
+
};
|
|
851
903
|
|
|
852
904
|
const { pathname, search, state } = useLocation();
|
|
853
905
|
```
|
|
906
|
+
|
|
854
907
|
### Where you came from
|
|
855
908
|
|
|
856
909
|
Every `location` carries `prevLocation` — the pathname and search of the route you
|
|
@@ -860,16 +913,16 @@ navigated away from. Useful for a contextual "Back" link, or for redirect logic
|
|
|
860
913
|
```tsx
|
|
861
914
|
const location = useLocation();
|
|
862
915
|
|
|
863
|
-
<Link to={location.prevLocation?.pathname ?? '/'}>← Back</Link
|
|
916
|
+
<Link to={location.prevLocation?.pathname ?? '/'}>← Back</Link>;
|
|
864
917
|
```
|
|
865
918
|
|
|
866
919
|
```tsx
|
|
867
920
|
// beforeLoad
|
|
868
921
|
beforeLoad: async ({ location, redirect }) => {
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
}
|
|
922
|
+
if (!isAuthenticated && location.prevLocation?.pathname !== '/login') {
|
|
923
|
+
await redirect('/login');
|
|
924
|
+
}
|
|
925
|
+
};
|
|
873
926
|
```
|
|
874
927
|
|
|
875
928
|
> `prevLocation` reflects only the immediately preceding route — it doesn't accumulate
|
|
@@ -882,11 +935,11 @@ Returns the cached data loaded by the current route's `loader`, along with any e
|
|
|
882
935
|
|
|
883
936
|
**Returns:**
|
|
884
937
|
|
|
885
|
-
| Property
|
|
886
|
-
|
|
887
|
-
| `data`
|
|
888
|
-
| `loaderError`
|
|
889
|
-
| `beforeLoadError` | `Error \| null` | Error from the `beforeLoad` hook (if any)
|
|
938
|
+
| Property | Type | Description |
|
|
939
|
+
| ----------------- | :-------------: | ------------------------------------------- |
|
|
940
|
+
| `data` | `T` | The data returned from the route's `loader` |
|
|
941
|
+
| `loaderError` | `Error \| null` | Error from the `loader` (if any) |
|
|
942
|
+
| `beforeLoadError` | `Error \| null` | Error from the `beforeLoad` hook (if any) |
|
|
890
943
|
|
|
891
944
|
```tsx
|
|
892
945
|
const UserProfile = () => {
|
|
@@ -913,7 +966,6 @@ const UserProfile = () => {
|
|
|
913
966
|
<Router routes={routes} maxCacheSize={200} />
|
|
914
967
|
```
|
|
915
968
|
|
|
916
|
-
|
|
917
969
|
### `useCacheSnapshot()`
|
|
918
970
|
|
|
919
971
|
Returns a read-only snapshot of the loader cache — intended for devtools panels, debugging, and cache
|
|
@@ -923,36 +975,36 @@ monitoring. Requires `<Router enableCacheSnapshot>`; while the flag is off the s
|
|
|
923
975
|
import { useCacheSnapshot } from 'clear-react-router';
|
|
924
976
|
|
|
925
977
|
const CachePanel = () => {
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
978
|
+
const entries = useCacheSnapshot();
|
|
979
|
+
|
|
980
|
+
return (
|
|
981
|
+
<ul>
|
|
982
|
+
{entries.map(entry => (
|
|
983
|
+
<li key={entry.path}>
|
|
984
|
+
{entry.path} — {entry.reason ?? 'unknown'} —{' '}
|
|
985
|
+
{entry.isCached ? (entry.isLoading ? 'revalidating' : 'cached') : 'loading'}
|
|
986
|
+
</li>
|
|
987
|
+
))}
|
|
988
|
+
</ul>
|
|
989
|
+
);
|
|
938
990
|
};
|
|
939
991
|
|
|
940
|
-
<Router routes={routes} enableCacheSnapshot
|
|
992
|
+
<Router routes={routes} enableCacheSnapshot />;
|
|
941
993
|
```
|
|
942
994
|
|
|
943
995
|
```ts
|
|
944
996
|
type CacheReason = 'navigation' | 'prefetch' | 'invalidate' | 'polling';
|
|
945
997
|
|
|
946
998
|
type CacheSnapshotEntry = {
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
999
|
+
path: string; // pathname + search
|
|
1000
|
+
data: unknown; // loader result; undefined while the first load is in flight
|
|
1001
|
+
timestamp: number; // when the entry was written (ms since epoch)
|
|
1002
|
+
staleTime: number | undefined; // effective freshness window: prefetch grace, route/default staleTime, or 0 for externalCache
|
|
1003
|
+
reason?: CacheReason; // what wrote the entry last
|
|
1004
|
+
gcExpiresAt: number | undefined; // GC deadline, if a GC timer is pending
|
|
1005
|
+
gcDuration: number | undefined; // the route's gcTime, for progress display
|
|
1006
|
+
isCached: boolean; // a loader result exists in memory (fresh or stale)
|
|
1007
|
+
isLoading: boolean; // a loader for this path is currently running
|
|
956
1008
|
};
|
|
957
1009
|
|
|
958
1010
|
type CacheSnapshot = CacheSnapshotEntry[];
|
|
@@ -1023,6 +1075,8 @@ This revalidates all cached routes such as:
|
|
|
1023
1075
|
Pattern-based invalidation is cache-only: it never sends `:param`/`[param]` to a loader.
|
|
1024
1076
|
If no cached route matches, nothing is fetched.
|
|
1025
1077
|
|
|
1078
|
+
> 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.
|
|
1079
|
+
|
|
1026
1080
|
This also works for nested dynamic routes:
|
|
1027
1081
|
|
|
1028
1082
|
```tsx
|
|
@@ -1030,6 +1084,7 @@ await invalidate('/post/[id]/comment/:commentId');
|
|
|
1030
1084
|
```
|
|
1031
1085
|
|
|
1032
1086
|
#### Force revalidation
|
|
1087
|
+
|
|
1033
1088
|
By default concrete pathnames are always revalidated, even if they were never cached
|
|
1034
1089
|
— this also makes `invalidate()` work on an error page with an empty cache.
|
|
1035
1090
|
Pass `{ force: false }` to go back to cache-only revalidation:
|
|
@@ -1042,11 +1097,14 @@ Explicit `{ force: true }` behaves the same as the default for concrete paths. P
|
|
|
1042
1097
|
targets stay cache-only regardless of `force`.
|
|
1043
1098
|
|
|
1044
1099
|
#### Stale-only revalidation
|
|
1100
|
+
|
|
1045
1101
|
By default, `invalidate` deletes matching cache entries and refetches them.
|
|
1046
1102
|
Pass `{ staleOnly: true }` to only revalidate entries that are already stale, leaving fresh ones untouched:
|
|
1103
|
+
|
|
1047
1104
|
```tsx
|
|
1048
1105
|
await invalidate('/notes', { staleOnly: true });
|
|
1049
1106
|
```
|
|
1107
|
+
|
|
1050
1108
|
Note: `staleOnly` disables the default force — uncached paths are left alone, so no new
|
|
1051
1109
|
network requests are started for routes you never visited.
|
|
1052
1110
|
|
|
@@ -1083,6 +1141,7 @@ will revalidate the cached child routes:
|
|
|
1083
1141
|
/post/23
|
|
1084
1142
|
/post/42/comments
|
|
1085
1143
|
```
|
|
1144
|
+
|
|
1086
1145
|
#### Status transitions
|
|
1087
1146
|
|
|
1088
1147
|
When the revalidated path matches the currently active `pathname + search`, a successful
|
|
@@ -1101,17 +1160,23 @@ cached search variant of that pathname.
|
|
|
1101
1160
|
#### Returns
|
|
1102
1161
|
|
|
1103
1162
|
An array of objects with the following structure:
|
|
1163
|
+
|
|
1104
1164
|
```ts
|
|
1105
|
-
{
|
|
1165
|
+
{
|
|
1166
|
+
path: string;
|
|
1167
|
+
data: unknown;
|
|
1168
|
+
error: unknown;
|
|
1169
|
+
}
|
|
1106
1170
|
```
|
|
1171
|
+
|
|
1107
1172
|
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.
|
|
1108
1173
|
|
|
1109
1174
|
#### Notes
|
|
1110
1175
|
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1176
|
+
- 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**.
|
|
1177
|
+
- With `{ staleOnly: true }`, uncached paths are never fetched — the default force does not apply.
|
|
1178
|
+
- Cached data is cleared before the new loader starts.
|
|
1179
|
+
- When used as an event handler, wrap the call in an arrow function:
|
|
1115
1180
|
|
|
1116
1181
|
```tsx
|
|
1117
1182
|
<button onClick={() => invalidate()}>Refresh</button>
|
|
@@ -1119,7 +1184,6 @@ Each object represents a revalidated route, where `path` is the route pathname,
|
|
|
1119
1184
|
|
|
1120
1185
|
Passing `invalidate` directly (`onClick={invalidate}`) is not supported because React passes a `MouseEvent` object to event handlers.
|
|
1121
1186
|
|
|
1122
|
-
|
|
1123
1187
|
### `useBlocker(callback)`
|
|
1124
1188
|
|
|
1125
1189
|
Blocks navigation - including the browser's Back/Forward buttons - while `callback` returns `true`.
|
|
@@ -1127,7 +1191,7 @@ Blocks navigation - including the browser's Back/Forward buttons - while `callba
|
|
|
1127
1191
|
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:
|
|
1128
1192
|
|
|
1129
1193
|
```ts
|
|
1130
|
-
callback: (arg: { location: Location; nextLocation: Location | null; context: Record<string, unknown> }) => boolean
|
|
1194
|
+
callback: (arg: { location: Location; nextLocation: Location | null; context: Record<string, unknown> }) => boolean;
|
|
1131
1195
|
```
|
|
1132
1196
|
|
|
1133
1197
|
- `location` - the route the user is currently on.
|
|
@@ -1136,28 +1200,30 @@ callback: (arg: { location: Location; nextLocation: Location | null; context: Re
|
|
|
1136
1200
|
|
|
1137
1201
|
**Returns:**
|
|
1138
1202
|
|
|
1139
|
-
| Property
|
|
1140
|
-
|
|
1141
|
-
| `state`
|
|
1142
|
-
| `process()` | `() => void`
|
|
1143
|
-
| `reset()`
|
|
1203
|
+
| Property | Type | Description |
|
|
1204
|
+
| ----------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1205
|
+
| `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. |
|
|
1206
|
+
| `process()` | `() => void` | Confirm and complete the blocked navigation |
|
|
1207
|
+
| `reset()` | `() => void` | Cancel the blocked navigation and stay on the current route |
|
|
1144
1208
|
|
|
1145
1209
|
```tsx
|
|
1146
1210
|
const { state, process, reset } = useBlocker(({ nextLocation }) => hasUnsavedChanges);
|
|
1147
1211
|
|
|
1148
1212
|
useEffect(() => {
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1213
|
+
if (state === 'blocked') {
|
|
1214
|
+
// Show your custom modal
|
|
1215
|
+
if (confirm('Leave without saving?')) {
|
|
1216
|
+
process();
|
|
1217
|
+
} else {
|
|
1218
|
+
reset();
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1157
1221
|
}, [state, process, reset]);
|
|
1158
1222
|
```
|
|
1159
1223
|
|
|
1160
1224
|
> 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.
|
|
1225
|
+
>
|
|
1226
|
+
> **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.
|
|
1161
1227
|
|
|
1162
1228
|
### Custom Blocker component
|
|
1163
1229
|
|
|
@@ -1165,19 +1231,19 @@ If you'd rather not manage the `useEffect` or conditional rendering yourself, yo
|
|
|
1165
1231
|
|
|
1166
1232
|
```tsx
|
|
1167
1233
|
type BlockerProps = {
|
|
1168
|
-
|
|
1169
|
-
|
|
1234
|
+
children: (blocker: ReturnType<typeof useBlocker>) => ReactNode;
|
|
1235
|
+
callback: (args: BlockerCallback) => boolean;
|
|
1170
1236
|
};
|
|
1171
1237
|
|
|
1172
1238
|
const Blocker = ({ callback, children }: BlockerProps) => {
|
|
1173
|
-
|
|
1174
|
-
|
|
1239
|
+
const blocker = useBlocker(callback);
|
|
1240
|
+
return blocker.state === 'blocked' ? children(blocker) : null;
|
|
1175
1241
|
};
|
|
1176
1242
|
```
|
|
1177
1243
|
|
|
1178
1244
|
```tsx
|
|
1179
1245
|
<Blocker callback={() => formState.isDirty}>
|
|
1180
|
-
|
|
1246
|
+
{({ process, reset }) => <Dialog onConfirm={process} onClose={reset} />}
|
|
1181
1247
|
</Blocker>
|
|
1182
1248
|
```
|
|
1183
1249
|
|
|
@@ -1187,50 +1253,50 @@ Returns a callback that restores the saved scroll position for the current route
|
|
|
1187
1253
|
|
|
1188
1254
|
The automatic restore covers content that is ready when navigation finishes (including route `loader` data). Call the callback yourself for content that arrives later:
|
|
1189
1255
|
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1256
|
+
- deferred data streamed via React 19 `use()`,
|
|
1257
|
+
- lazily loaded route chunks,
|
|
1258
|
+
- any container that mounts after the initial render.
|
|
1193
1259
|
|
|
1194
1260
|
```tsx
|
|
1195
1261
|
import { useRestoreScroll, useLoaderState } from 'clear-react-router';
|
|
1196
1262
|
|
|
1197
1263
|
const SlowTable = () => {
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1264
|
+
const restoreScroll = useRestoreScroll();
|
|
1265
|
+
const { data } = useLoaderState<{ rows: Promise<Row[]> }>();
|
|
1266
|
+
|
|
1267
|
+
return (
|
|
1268
|
+
<Suspense fallback={<Skeleton />}>
|
|
1269
|
+
<Table rows={data.rows} onReady={restoreScroll} />
|
|
1270
|
+
</Suspense>
|
|
1271
|
+
);
|
|
1206
1272
|
};
|
|
1207
1273
|
```
|
|
1208
1274
|
|
|
1209
|
-
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
|
|
1275
|
+
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:
|
|
1210
1276
|
|
|
1211
1277
|
```tsx
|
|
1212
1278
|
const Dashboard = () => {
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1279
|
+
const restoreScroll = useRestoreScroll();
|
|
1280
|
+
const [rows, setRows] = useState<Row[] | null>(null);
|
|
1281
|
+
|
|
1282
|
+
useEffect(() => {
|
|
1283
|
+
fetchRows().then(data => {
|
|
1284
|
+
setRows(data);
|
|
1285
|
+
// DOM updates after setState — wait a frame so the container exists
|
|
1286
|
+
requestAnimationFrame(() => restoreScroll());
|
|
1287
|
+
});
|
|
1288
|
+
}, [restoreScroll]);
|
|
1289
|
+
|
|
1290
|
+
return rows ? <Table rows={rows} /> : <Skeleton />;
|
|
1225
1291
|
};
|
|
1226
1292
|
```
|
|
1227
1293
|
|
|
1228
1294
|
Details worth knowing:
|
|
1229
1295
|
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1296
|
+
- 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.
|
|
1297
|
+
- 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`.
|
|
1298
|
+
- 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.
|
|
1299
|
+
- 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.
|
|
1234
1300
|
|
|
1235
1301
|
### `useRouteStatus()`
|
|
1236
1302
|
|
|
@@ -1249,13 +1315,13 @@ To render your own loading indicator (for example next to a link while its targe
|
|
|
1249
1315
|
import { Link, useRouteStatus } from 'clear-react-router';
|
|
1250
1316
|
|
|
1251
1317
|
const NavLink = ({ to, children }: { to: string; children: ReactNode }) => {
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1318
|
+
const isLoading = useRouteStatus(status => status === 'pending' || status === 'optimistic');
|
|
1319
|
+
return (
|
|
1320
|
+
<Link to={to} className={({ isPending }) => (isPending ? 'link-pending' : '')}>
|
|
1321
|
+
{children}
|
|
1322
|
+
{isLoading && <span aria-hidden="true"> •••</span>}
|
|
1323
|
+
</Link>
|
|
1324
|
+
);
|
|
1259
1325
|
};
|
|
1260
1326
|
```
|
|
1261
1327
|
|
|
@@ -1266,6 +1332,7 @@ For per-link pending styling without custom components, `pendingClassName` and t
|
|
|
1266
1332
|
### `useRouterContext()`
|
|
1267
1333
|
|
|
1268
1334
|
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.
|
|
1335
|
+
|
|
1269
1336
|
```tsx
|
|
1270
1337
|
const { setContext, context } = useRouterContext();
|
|
1271
1338
|
const loginHandler = () => setContext({ ...context, user: { name: 'John' } });
|
|
@@ -1279,34 +1346,35 @@ Returns an object for working with URL query parameters. Supports reading and se
|
|
|
1279
1346
|
import { useSearchParams } from 'clear-react-router';
|
|
1280
1347
|
|
|
1281
1348
|
function ProductFilter() {
|
|
1282
|
-
|
|
1349
|
+
const { searchParams, getSearchParams, setSearchParams } = useSearchParams();
|
|
1283
1350
|
|
|
1284
|
-
|
|
1285
|
-
|
|
1351
|
+
// Get a single value or array
|
|
1352
|
+
const brand = getSearchParams('brand'); // 'nike' | ['nike', 'reebok'] | ''
|
|
1286
1353
|
|
|
1287
|
-
|
|
1288
|
-
|
|
1354
|
+
// Set a single value
|
|
1355
|
+
setSearchParams('brand', 'nike'); // ?brand=nike
|
|
1289
1356
|
|
|
1290
|
-
|
|
1291
|
-
|
|
1357
|
+
// Set multiple values (array)
|
|
1358
|
+
setSearchParams('brand', ['nike', 'reebok']); // ?brand=nike&brand=reebok
|
|
1292
1359
|
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1360
|
+
// Functional update (preserves other params)
|
|
1361
|
+
setSearchParams(prev => {
|
|
1362
|
+
prev.set('page', '2');
|
|
1363
|
+
prev.append('color', 'red');
|
|
1364
|
+
return prev;
|
|
1365
|
+
});
|
|
1299
1366
|
|
|
1300
|
-
|
|
1301
|
-
|
|
1367
|
+
// Direct access to URLSearchParams
|
|
1368
|
+
const allParams = searchParams.toString(); // "brand=nike&brand=reebok&page=2"
|
|
1302
1369
|
}
|
|
1303
1370
|
```
|
|
1371
|
+
|
|
1304
1372
|
**Returns:**
|
|
1305
1373
|
|
|
1306
|
-
| Property
|
|
1307
|
-
|
|
1308
|
-
| `searchParams`
|
|
1309
|
-
| `getSearchParams` | `(key: string) => string \| string[]`
|
|
1374
|
+
| Property | Type | Description |
|
|
1375
|
+
| ----------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
|
|
1376
|
+
| `searchParams` | `URLSearchParams` | Raw `URLSearchParams` object for low-level access |
|
|
1377
|
+
| `getSearchParams` | `(key: string) => string \| string[]` | Returns a single value or an array if multiple values exist for the key |
|
|
1310
1378
|
| `setSearchParams` | `(param: string, value: string \| string[]) => void` `or` `(updater: (prev: URLSearchParams) => URLSearchParams) => void` | Update query parameters. Supports single values, arrays, or functional updates |
|
|
1311
1379
|
|
|
1312
1380
|
**Key features:**
|
|
@@ -1321,23 +1389,23 @@ function ProductFilter() {
|
|
|
1321
1389
|
|
|
1322
1390
|
```tsx
|
|
1323
1391
|
function ProductFilter() {
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1392
|
+
const { searchParams, setSearchParams } = useSearchParams();
|
|
1393
|
+
const { pathname } = useLocation();
|
|
1394
|
+
const navigate = useNavigate();
|
|
1395
|
+
const invalidate = useInvalidate();
|
|
1396
|
+
|
|
1397
|
+
// Full navigation: runs beforeLoad / loader / afterLoad and pushes a history entry
|
|
1398
|
+
const applyFilter = () => {
|
|
1399
|
+
const next = new URLSearchParams(searchParams);
|
|
1400
|
+
next.set('brand', 'nike');
|
|
1401
|
+
navigate({ pathname, search: `?${next.toString()}` });
|
|
1402
|
+
};
|
|
1403
|
+
|
|
1404
|
+
// Explicit revalidation: keeps the history entry, reruns the loader, skips beforeLoad / afterLoad
|
|
1405
|
+
const revalidateFilter = async () => {
|
|
1406
|
+
setSearchParams('brand', 'nike');
|
|
1407
|
+
await invalidate();
|
|
1408
|
+
};
|
|
1341
1409
|
}
|
|
1342
1410
|
```
|
|
1343
1411
|
|
|
@@ -1346,6 +1414,7 @@ function ProductFilter() {
|
|
|
1346
1414
|
## Lazy Loading
|
|
1347
1415
|
|
|
1348
1416
|
Clear Router supports code-splitting out of the box. Simply wrap dynamic import into a library's `lazy` function:
|
|
1417
|
+
|
|
1349
1418
|
```tsx
|
|
1350
1419
|
import { lazy } from 'clear-react-router';
|
|
1351
1420
|
|
|
@@ -1375,14 +1444,14 @@ fast data while slow data streams in separately:
|
|
|
1375
1444
|
|
|
1376
1445
|
```tsx
|
|
1377
1446
|
const Slow = () => {
|
|
1378
|
-
|
|
1379
|
-
|
|
1447
|
+
const { data } = useLoaderState<{ slow: Promise<string> }>();
|
|
1448
|
+
return use(data.slow);
|
|
1380
1449
|
};
|
|
1381
1450
|
|
|
1382
1451
|
const About = () => (
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1452
|
+
<Suspense fallback={<Skeleton />}>
|
|
1453
|
+
<Slow />
|
|
1454
|
+
</Suspense>
|
|
1386
1455
|
);
|
|
1387
1456
|
```
|
|
1388
1457
|
|
|
@@ -1411,6 +1480,7 @@ View Transitions API requires modern browsers:
|
|
|
1411
1480
|
For older browsers, the router gracefully falls back to regular navigation without animation.
|
|
1412
1481
|
|
|
1413
1482
|
## Requirements
|
|
1483
|
+
|
|
1414
1484
|
- React 16.8+ (for React.lazy and Suspense)
|
|
1415
1485
|
- Use `default` export for your lazy-loaded components
|
|
1416
1486
|
|
|
@@ -1425,5 +1495,6 @@ LRU eviction with a tiny cache, gcTime cleanup, an invalidation lab, a live cach
|
|
|
1425
1495
|
in-browser server.
|
|
1426
1496
|
Open devtools and click around.
|
|
1427
1497
|
|
|
1428
|
-
|
|
1429
|
-
|
|
1498
|
+
## License
|
|
1499
|
+
|
|
1500
|
+
MIT
|