clear-react-router 2.5.5 → 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 +471 -401
- package/dist/components/Router.d.ts +1 -1
- package/dist/config/routerConfig.d.ts +1 -0
- package/dist/index.js +91 -38
- 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,30 @@ 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
|
-
| `children`
|
|
268
|
-
| `className`
|
|
269
|
-
| `style`
|
|
270
|
-
| `activeClassName`
|
|
271
|
-
| `pendingClassName`
|
|
272
|
-
| `beforeNavigate`
|
|
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 |
|
|
273
323
|
|
|
274
324
|
**State values:**
|
|
275
325
|
|
|
276
|
-
| State
|
|
277
|
-
|
|
278
|
-
| `isActive`
|
|
279
|
-
| `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) |
|
|
280
330
|
|
|
281
331
|
### Accessibility
|
|
282
332
|
|
|
@@ -286,7 +336,7 @@ Extra `data-*` and `aria-*` props passed to `<Link>` (e.g. `data-testid`, `aria-
|
|
|
286
336
|
|
|
287
337
|
```tsx
|
|
288
338
|
<Link to="/about" aria-label="About section" data-testid="about-link">
|
|
289
|
-
|
|
339
|
+
About
|
|
290
340
|
</Link>
|
|
291
341
|
```
|
|
292
342
|
|
|
@@ -294,14 +344,14 @@ When using a custom element via `as`, these attributes arrive in `props` togethe
|
|
|
294
344
|
|
|
295
345
|
### Prefetch Strategies
|
|
296
346
|
|
|
297
|
-
| Strategy
|
|
298
|
-
|
|
299
|
-
| `'hover'`
|
|
300
|
-
| `'render'`
|
|
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 |
|
|
301
351
|
| `'viewport'` | Prefetches when the link enters the viewport (using Intersection Observer) |
|
|
302
|
-
| `'none'`
|
|
352
|
+
| `'none'` | No prefetching |
|
|
303
353
|
|
|
304
|
-
> A prefetched entry is considered fresh for 30 seconds. The first navigation within
|
|
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.
|
|
305
355
|
|
|
306
356
|
### Custom elements via `as`
|
|
307
357
|
|
|
@@ -314,23 +364,19 @@ When using `as` to render a custom component instead of the default `<a>`, your
|
|
|
314
364
|
|
|
315
365
|
```tsx
|
|
316
366
|
// ✅ correct — every prop is forwarded to the host element
|
|
317
|
-
const Button = ({ children, ...props }: ElementProps<HTMLButtonElement>) =>
|
|
318
|
-
<button {...props}>{children}</button>
|
|
319
|
-
);
|
|
367
|
+
const Button = ({ children, ...props }: ElementProps<HTMLButtonElement>) => <button {...props}>{children}</button>;
|
|
320
368
|
|
|
321
369
|
// ❌ wrong — ref, event handlers, and href are silently dropped
|
|
322
|
-
const Button = ({ children }: { children: ReactNode }) =>
|
|
323
|
-
<button>{children}</button>
|
|
324
|
-
);
|
|
370
|
+
const Button = ({ children }: { children: ReactNode }) => <button>{children}</button>;
|
|
325
371
|
```
|
|
326
372
|
|
|
327
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:
|
|
328
374
|
|
|
329
375
|
```tsx
|
|
330
376
|
const Button = ({ children, ...props }: ElementProps<HTMLButtonElement>) => (
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
377
|
+
<button {...props} className={`btn ${props.className ?? ''}`}>
|
|
378
|
+
{children}
|
|
379
|
+
</button>
|
|
334
380
|
);
|
|
335
381
|
```
|
|
336
382
|
|
|
@@ -364,6 +410,7 @@ import { Button } from '@mui/material';
|
|
|
364
410
|
To about page
|
|
365
411
|
</Link>
|
|
366
412
|
```
|
|
413
|
+
|
|
367
414
|
### Styling link states with CSS
|
|
368
415
|
|
|
369
416
|
Before reaching for `as`, check whether CSS is enough: active and loading states are already
|
|
@@ -374,25 +421,25 @@ screen readers) intact:
|
|
|
374
421
|
|
|
375
422
|
```tsx
|
|
376
423
|
<Link to="/playground/settings" aria-label="Settings" className="gear-link">
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
424
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true">
|
|
425
|
+
<path d="..." />
|
|
426
|
+
</svg>
|
|
380
427
|
</Link>
|
|
381
428
|
```
|
|
382
429
|
|
|
383
430
|
```css
|
|
384
431
|
/* Active page — no state plumbing needed */
|
|
385
432
|
.gear-link[aria-current='page'] {
|
|
386
|
-
|
|
433
|
+
color: steelblue;
|
|
387
434
|
}
|
|
388
435
|
/* CSS beats SVG presentation attributes (fill="none"), so this fills the icon: */
|
|
389
436
|
.gear-link[aria-current='page'] svg {
|
|
390
|
-
|
|
391
|
-
|
|
437
|
+
fill: steelblue;
|
|
438
|
+
stroke: steelblue;
|
|
392
439
|
}
|
|
393
440
|
/* Target is loading: */
|
|
394
441
|
.gear-link[aria-busy='true'] {
|
|
395
|
-
|
|
442
|
+
opacity: 0.6;
|
|
396
443
|
}
|
|
397
444
|
```
|
|
398
445
|
|
|
@@ -445,6 +492,7 @@ Reach for `as` only when the element itself must change (a `<button>`, a UI-kit
|
|
|
445
492
|
Settings
|
|
446
493
|
</Link>
|
|
447
494
|
```
|
|
495
|
+
|
|
448
496
|
**Important**: prefetch="render" should be used sparingly, as it preloads data immediately when the link is rendered, which may cause unnecessary network requests.
|
|
449
497
|
|
|
450
498
|
## Retry
|
|
@@ -498,10 +546,10 @@ Unlike many routing libraries, retry is **not limited to the initial loader exec
|
|
|
498
546
|
|
|
499
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:
|
|
500
548
|
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
549
|
+
- Initial route loading
|
|
550
|
+
- Cache revalidation
|
|
551
|
+
- `invalidate()`
|
|
552
|
+
- `prefetch()`
|
|
505
553
|
|
|
506
554
|
This ensures consistent behavior regardless of how the data is being refreshed.
|
|
507
555
|
|
|
@@ -519,40 +567,39 @@ Function provided to `beforeLoad` for programmatic redirection.
|
|
|
519
567
|
import type { createRouter } from 'clear-react-router';
|
|
520
568
|
|
|
521
569
|
const routes = createRouter([
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
570
|
+
{
|
|
571
|
+
path: '/dashboard',
|
|
572
|
+
element: <Dashboard />,
|
|
573
|
+
beforeLoad: ({ context, redirect }) => {
|
|
574
|
+
if (!context.isAuthorized) return redirect('/');
|
|
575
|
+
},
|
|
576
|
+
},
|
|
529
577
|
]);
|
|
530
578
|
|
|
531
579
|
const routes = createRouter([
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
580
|
+
{
|
|
581
|
+
path: '/dashboard',
|
|
582
|
+
element: <Dashboard />,
|
|
583
|
+
beforeLoad: ({ context, redirect }) => {
|
|
584
|
+
if (!context.isAuthorized) return redirect({ pathname: '/login', state: { from: '/dashboard' } });
|
|
585
|
+
},
|
|
586
|
+
},
|
|
539
587
|
]);
|
|
540
588
|
|
|
541
589
|
const routes = createRouter([
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
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
|
+
},
|
|
554
602
|
]);
|
|
555
|
-
|
|
556
603
|
```
|
|
557
604
|
|
|
558
605
|
### Usage with Parameters
|
|
@@ -563,29 +610,29 @@ The `loader`, `beforeLoad`, and `afterLoad` hooks receive `params` (extracted fr
|
|
|
563
610
|
import type { createRouter } from 'clear-react-router';
|
|
564
611
|
|
|
565
612
|
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
|
-
|
|
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
|
+
},
|
|
589
636
|
]);
|
|
590
637
|
```
|
|
591
638
|
|
|
@@ -606,11 +653,11 @@ actions?: ({ params, context, searchParams, setContext, location }) => ({
|
|
|
606
653
|
|
|
607
654
|
```ts
|
|
608
655
|
{
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
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
|
|
614
661
|
}
|
|
615
662
|
```
|
|
616
663
|
|
|
@@ -626,15 +673,15 @@ A record where each key is an action name and each value is a function accepting
|
|
|
626
673
|
import { useSubmitAction } from 'clear-react-router';
|
|
627
674
|
|
|
628
675
|
const CreateUserForm = () => {
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
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
|
+
);
|
|
638
685
|
};
|
|
639
686
|
```
|
|
640
687
|
|
|
@@ -647,28 +694,28 @@ const { register, handleSubmit } = useForm<FormValues>();
|
|
|
647
694
|
const { submit, isSubmitting } = useSubmitAction('createUser');
|
|
648
695
|
|
|
649
696
|
<form onSubmit={handleSubmit(submit)}>
|
|
650
|
-
|
|
651
|
-
</form
|
|
697
|
+
<input {...register('email')} disabled={isSubmitting} />
|
|
698
|
+
</form>;
|
|
652
699
|
```
|
|
653
700
|
|
|
654
701
|
Arguments:
|
|
655
702
|
|
|
656
|
-
| Argument
|
|
657
|
-
|
|
658
|
-
| `action`
|
|
659
|
-
| `options.onSuccess` | `(data: unknown) => void \| undefined`
|
|
660
|
-
| `options.onError`
|
|
661
|
-
| `options.autoReset` | `boolean \| undefined`
|
|
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`) |
|
|
662
709
|
|
|
663
710
|
Return value:
|
|
664
711
|
|
|
665
|
-
| Field
|
|
666
|
-
|
|
667
|
-
| `submit`
|
|
668
|
-
| `onSubmit`
|
|
669
|
-
| `data`
|
|
670
|
-
| `error`
|
|
671
|
-
| `isSubmitting` | `boolean`
|
|
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 |
|
|
672
719
|
|
|
673
720
|
> The native `onSubmit` handler converts the form via `Object.fromEntries(new FormData(...))` —
|
|
674
721
|
> if your form has multiple fields sharing the same `name` (checkbox groups, `<select multiple>`),
|
|
@@ -681,10 +728,10 @@ Return value:
|
|
|
681
728
|
|
|
682
729
|
### Arguments
|
|
683
730
|
|
|
684
|
-
| Argument
|
|
685
|
-
|
|
686
|
-
| `action`
|
|
687
|
-
| `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. |
|
|
688
735
|
|
|
689
736
|
```ts
|
|
690
737
|
type Options = { onSuccess?: (args: unknown) => void; onError?: (args: unknown) => void };
|
|
@@ -694,14 +741,13 @@ type Options = { onSuccess?: (args: unknown) => void; onError?: (args: unknown)
|
|
|
694
741
|
const save = useAction('save');
|
|
695
742
|
const handleClick = async () => await save({ data: 'Hello world!' });
|
|
696
743
|
|
|
697
|
-
<button onClick={handleClick}>Save</button
|
|
744
|
+
<button onClick={handleClick}>Save</button>;
|
|
698
745
|
```
|
|
699
746
|
|
|
700
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.
|
|
701
748
|
|
|
702
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.
|
|
703
750
|
|
|
704
|
-
|
|
705
751
|
### Error Boundaries
|
|
706
752
|
|
|
707
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.
|
|
@@ -711,8 +757,9 @@ import { Router } from 'clear-react-router';
|
|
|
711
757
|
import { routes } from './routes';
|
|
712
758
|
import { ErrorBoundary } from './components/ErrorBoundary';
|
|
713
759
|
|
|
714
|
-
const App = () => <Router routes={routes} errorBoundary={ErrorBoundary}
|
|
760
|
+
const App = () => <Router routes={routes} errorBoundary={ErrorBoundary} />;
|
|
715
761
|
```
|
|
762
|
+
|
|
716
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.
|
|
717
764
|
|
|
718
765
|
## Hooks
|
|
@@ -722,13 +769,17 @@ const App = () => <Router routes={routes} errorBoundary={ErrorBoundary} />
|
|
|
722
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.
|
|
723
770
|
|
|
724
771
|
```tsx
|
|
725
|
-
type NavigationLocation = {
|
|
772
|
+
type NavigationLocation = {
|
|
773
|
+
pathname: string;
|
|
774
|
+
search?: string | Record<string, string | number | boolean | null | undefined>;
|
|
775
|
+
state?: unknown;
|
|
776
|
+
};
|
|
726
777
|
|
|
727
778
|
const navigate = useNavigate();
|
|
728
779
|
|
|
729
|
-
navigate('/about');
|
|
730
|
-
navigate({ pathname: '/user/123', search: { user: 'Jane Doe' }, state: { from: 'home' } });
|
|
731
|
-
navigate(-1);
|
|
780
|
+
navigate('/about'); // string
|
|
781
|
+
navigate({ pathname: '/user/123', search: { user: 'Jane Doe' }, state: { from: 'home' } }); // NavigationLocation
|
|
782
|
+
navigate(-1); // go back
|
|
732
783
|
```
|
|
733
784
|
|
|
734
785
|
**Note:** Navigation state can be accessed via [`useLocation()`](#uselocation):
|
|
@@ -765,7 +816,7 @@ navigation, pass a route pattern via `path` with matching `params` instead — t
|
|
|
765
816
|
interpolates the segments (values are URL-encoded, a missing param throws):
|
|
766
817
|
|
|
767
818
|
```tsx
|
|
768
|
-
<Link path="/product/:productId" params={{ productId: '7' }}
|
|
819
|
+
<Link path="/product/:productId" params={{ productId: '7' }} />;
|
|
769
820
|
navigate({ path: '/product/:productId', params: { productId: '7' } });
|
|
770
821
|
```
|
|
771
822
|
|
|
@@ -776,7 +827,7 @@ Declarative and imperative forms are equivalent — this link:
|
|
|
776
827
|
|
|
777
828
|
```tsx
|
|
778
829
|
<Link path="/nest/:nestId/item/:itemId" params={{ nestId, itemId }}>
|
|
779
|
-
|
|
830
|
+
{itemId}
|
|
780
831
|
</Link>
|
|
781
832
|
```
|
|
782
833
|
|
|
@@ -785,9 +836,7 @@ does the same as this button:
|
|
|
785
836
|
```tsx
|
|
786
837
|
const navigate = useNavigate();
|
|
787
838
|
|
|
788
|
-
<button onClick={() => navigate({ path: '/nest/:nestId/item/:itemId', params: { nestId, itemId } })}>
|
|
789
|
-
{itemId}
|
|
790
|
-
</button>
|
|
839
|
+
<button onClick={() => navigate({ path: '/nest/:nestId/item/:itemId', params: { nestId, itemId } })}>{itemId}</button>;
|
|
791
840
|
```
|
|
792
841
|
|
|
793
842
|
Same type-checking, same interpolation. Use links for navigation, buttons with `navigate`
|
|
@@ -802,37 +851,38 @@ userland pattern — adopt it ladder-style, each rung optional:
|
|
|
802
851
|
- **Rung 1 — `path` + `params` on plain `Link`.** No union, no wrapper, no setup:
|
|
803
852
|
TypeScript infers the pattern from the `path` literal itself and checks `params`
|
|
804
853
|
against it:
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
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.
|
|
817
866
|
- **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
867
|
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
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
|
+
|
|
825
874
|
- **Rung 3 — wrapper + union.** Binds one union for existence checking:
|
|
826
|
-
```tsx
|
|
827
|
-
type AppPaths = '/cache' | '/product/:productId';
|
|
828
875
|
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
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
|
+
);
|
|
832
882
|
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
883
|
+
<AppLink path="/product/:productId" params={{ productId: '7' }} /> // ok
|
|
884
|
+
<AppLink path="/playgroud/cache" /> // error: not in AppPaths
|
|
885
|
+
```
|
|
836
886
|
|
|
837
887
|
The union is generated by script or hand-written.
|
|
838
888
|
Keep it next to the routes so drift is visible in review; a forgotten path fails
|
|
@@ -841,16 +891,18 @@ compilation at usage (fail-closed), a leftover entry is harmless.
|
|
|
841
891
|
### `useLocation()`
|
|
842
892
|
|
|
843
893
|
Returns current location `{ pathname, search, state }`.
|
|
894
|
+
|
|
844
895
|
```tsx
|
|
845
896
|
type Location = {
|
|
846
897
|
pathname: string;
|
|
847
898
|
search?: string;
|
|
848
899
|
state?: unknown;
|
|
849
900
|
prevLocation?: Omit<Location, 'state' | 'prevLocation'>;
|
|
850
|
-
}
|
|
901
|
+
};
|
|
851
902
|
|
|
852
903
|
const { pathname, search, state } = useLocation();
|
|
853
904
|
```
|
|
905
|
+
|
|
854
906
|
### Where you came from
|
|
855
907
|
|
|
856
908
|
Every `location` carries `prevLocation` — the pathname and search of the route you
|
|
@@ -860,16 +912,16 @@ navigated away from. Useful for a contextual "Back" link, or for redirect logic
|
|
|
860
912
|
```tsx
|
|
861
913
|
const location = useLocation();
|
|
862
914
|
|
|
863
|
-
<Link to={location.prevLocation?.pathname ?? '/'}>← Back</Link
|
|
915
|
+
<Link to={location.prevLocation?.pathname ?? '/'}>← Back</Link>;
|
|
864
916
|
```
|
|
865
917
|
|
|
866
918
|
```tsx
|
|
867
919
|
// beforeLoad
|
|
868
920
|
beforeLoad: async ({ location, redirect }) => {
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
}
|
|
921
|
+
if (!isAuthenticated && location.prevLocation?.pathname !== '/login') {
|
|
922
|
+
await redirect('/login');
|
|
923
|
+
}
|
|
924
|
+
};
|
|
873
925
|
```
|
|
874
926
|
|
|
875
927
|
> `prevLocation` reflects only the immediately preceding route — it doesn't accumulate
|
|
@@ -882,11 +934,11 @@ Returns the cached data loaded by the current route's `loader`, along with any e
|
|
|
882
934
|
|
|
883
935
|
**Returns:**
|
|
884
936
|
|
|
885
|
-
| Property
|
|
886
|
-
|
|
887
|
-
| `data`
|
|
888
|
-
| `loaderError`
|
|
889
|
-
| `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) |
|
|
890
942
|
|
|
891
943
|
```tsx
|
|
892
944
|
const UserProfile = () => {
|
|
@@ -913,7 +965,6 @@ const UserProfile = () => {
|
|
|
913
965
|
<Router routes={routes} maxCacheSize={200} />
|
|
914
966
|
```
|
|
915
967
|
|
|
916
|
-
|
|
917
968
|
### `useCacheSnapshot()`
|
|
918
969
|
|
|
919
970
|
Returns a read-only snapshot of the loader cache — intended for devtools panels, debugging, and cache
|
|
@@ -923,36 +974,36 @@ monitoring. Requires `<Router enableCacheSnapshot>`; while the flag is off the s
|
|
|
923
974
|
import { useCacheSnapshot } from 'clear-react-router';
|
|
924
975
|
|
|
925
976
|
const CachePanel = () => {
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
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
|
+
);
|
|
938
989
|
};
|
|
939
990
|
|
|
940
|
-
<Router routes={routes} enableCacheSnapshot
|
|
991
|
+
<Router routes={routes} enableCacheSnapshot />;
|
|
941
992
|
```
|
|
942
993
|
|
|
943
994
|
```ts
|
|
944
995
|
type CacheReason = 'navigation' | 'prefetch' | 'invalidate' | 'polling';
|
|
945
996
|
|
|
946
997
|
type CacheSnapshotEntry = {
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
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
|
|
956
1007
|
};
|
|
957
1008
|
|
|
958
1009
|
type CacheSnapshot = CacheSnapshotEntry[];
|
|
@@ -1023,6 +1074,8 @@ This revalidates all cached routes such as:
|
|
|
1023
1074
|
Pattern-based invalidation is cache-only: it never sends `:param`/`[param]` to a loader.
|
|
1024
1075
|
If no cached route matches, nothing is fetched.
|
|
1025
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
|
+
|
|
1026
1079
|
This also works for nested dynamic routes:
|
|
1027
1080
|
|
|
1028
1081
|
```tsx
|
|
@@ -1030,6 +1083,7 @@ await invalidate('/post/[id]/comment/:commentId');
|
|
|
1030
1083
|
```
|
|
1031
1084
|
|
|
1032
1085
|
#### Force revalidation
|
|
1086
|
+
|
|
1033
1087
|
By default concrete pathnames are always revalidated, even if they were never cached
|
|
1034
1088
|
— this also makes `invalidate()` work on an error page with an empty cache.
|
|
1035
1089
|
Pass `{ force: false }` to go back to cache-only revalidation:
|
|
@@ -1042,11 +1096,14 @@ Explicit `{ force: true }` behaves the same as the default for concrete paths. P
|
|
|
1042
1096
|
targets stay cache-only regardless of `force`.
|
|
1043
1097
|
|
|
1044
1098
|
#### Stale-only revalidation
|
|
1099
|
+
|
|
1045
1100
|
By default, `invalidate` deletes matching cache entries and refetches them.
|
|
1046
1101
|
Pass `{ staleOnly: true }` to only revalidate entries that are already stale, leaving fresh ones untouched:
|
|
1102
|
+
|
|
1047
1103
|
```tsx
|
|
1048
1104
|
await invalidate('/notes', { staleOnly: true });
|
|
1049
1105
|
```
|
|
1106
|
+
|
|
1050
1107
|
Note: `staleOnly` disables the default force — uncached paths are left alone, so no new
|
|
1051
1108
|
network requests are started for routes you never visited.
|
|
1052
1109
|
|
|
@@ -1083,6 +1140,7 @@ will revalidate the cached child routes:
|
|
|
1083
1140
|
/post/23
|
|
1084
1141
|
/post/42/comments
|
|
1085
1142
|
```
|
|
1143
|
+
|
|
1086
1144
|
#### Status transitions
|
|
1087
1145
|
|
|
1088
1146
|
When the revalidated path matches the currently active `pathname + search`, a successful
|
|
@@ -1101,17 +1159,23 @@ cached search variant of that pathname.
|
|
|
1101
1159
|
#### Returns
|
|
1102
1160
|
|
|
1103
1161
|
An array of objects with the following structure:
|
|
1162
|
+
|
|
1104
1163
|
```ts
|
|
1105
|
-
{
|
|
1164
|
+
{
|
|
1165
|
+
path: string;
|
|
1166
|
+
data: unknown;
|
|
1167
|
+
error: unknown;
|
|
1168
|
+
}
|
|
1106
1169
|
```
|
|
1170
|
+
|
|
1107
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.
|
|
1108
1172
|
|
|
1109
1173
|
#### Notes
|
|
1110
1174
|
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
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:
|
|
1115
1179
|
|
|
1116
1180
|
```tsx
|
|
1117
1181
|
<button onClick={() => invalidate()}>Refresh</button>
|
|
@@ -1119,7 +1183,6 @@ Each object represents a revalidated route, where `path` is the route pathname,
|
|
|
1119
1183
|
|
|
1120
1184
|
Passing `invalidate` directly (`onClick={invalidate}`) is not supported because React passes a `MouseEvent` object to event handlers.
|
|
1121
1185
|
|
|
1122
|
-
|
|
1123
1186
|
### `useBlocker(callback)`
|
|
1124
1187
|
|
|
1125
1188
|
Blocks navigation - including the browser's Back/Forward buttons - while `callback` returns `true`.
|
|
@@ -1127,7 +1190,7 @@ Blocks navigation - including the browser's Back/Forward buttons - while `callba
|
|
|
1127
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:
|
|
1128
1191
|
|
|
1129
1192
|
```ts
|
|
1130
|
-
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;
|
|
1131
1194
|
```
|
|
1132
1195
|
|
|
1133
1196
|
- `location` - the route the user is currently on.
|
|
@@ -1136,28 +1199,30 @@ callback: (arg: { location: Location; nextLocation: Location | null; context: Re
|
|
|
1136
1199
|
|
|
1137
1200
|
**Returns:**
|
|
1138
1201
|
|
|
1139
|
-
| Property
|
|
1140
|
-
|
|
1141
|
-
| `state`
|
|
1142
|
-
| `process()` | `() => void`
|
|
1143
|
-
| `reset()`
|
|
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 |
|
|
1144
1207
|
|
|
1145
1208
|
```tsx
|
|
1146
1209
|
const { state, process, reset } = useBlocker(({ nextLocation }) => hasUnsavedChanges);
|
|
1147
1210
|
|
|
1148
1211
|
useEffect(() => {
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1212
|
+
if (state === 'blocked') {
|
|
1213
|
+
// Show your custom modal
|
|
1214
|
+
if (confirm('Leave without saving?')) {
|
|
1215
|
+
process();
|
|
1216
|
+
} else {
|
|
1217
|
+
reset();
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1157
1220
|
}, [state, process, reset]);
|
|
1158
1221
|
```
|
|
1159
1222
|
|
|
1160
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.
|
|
1161
1226
|
|
|
1162
1227
|
### Custom Blocker component
|
|
1163
1228
|
|
|
@@ -1165,19 +1230,19 @@ If you'd rather not manage the `useEffect` or conditional rendering yourself, yo
|
|
|
1165
1230
|
|
|
1166
1231
|
```tsx
|
|
1167
1232
|
type BlockerProps = {
|
|
1168
|
-
|
|
1169
|
-
|
|
1233
|
+
children: (blocker: ReturnType<typeof useBlocker>) => ReactNode;
|
|
1234
|
+
callback: (args: BlockerCallback) => boolean;
|
|
1170
1235
|
};
|
|
1171
1236
|
|
|
1172
1237
|
const Blocker = ({ callback, children }: BlockerProps) => {
|
|
1173
|
-
|
|
1174
|
-
|
|
1238
|
+
const blocker = useBlocker(callback);
|
|
1239
|
+
return blocker.state === 'blocked' ? children(blocker) : null;
|
|
1175
1240
|
};
|
|
1176
1241
|
```
|
|
1177
1242
|
|
|
1178
1243
|
```tsx
|
|
1179
1244
|
<Blocker callback={() => formState.isDirty}>
|
|
1180
|
-
|
|
1245
|
+
{({ process, reset }) => <Dialog onConfirm={process} onClose={reset} />}
|
|
1181
1246
|
</Blocker>
|
|
1182
1247
|
```
|
|
1183
1248
|
|
|
@@ -1187,50 +1252,50 @@ Returns a callback that restores the saved scroll position for the current route
|
|
|
1187
1252
|
|
|
1188
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:
|
|
1189
1254
|
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1255
|
+
- deferred data streamed via React 19 `use()`,
|
|
1256
|
+
- lazily loaded route chunks,
|
|
1257
|
+
- any container that mounts after the initial render.
|
|
1193
1258
|
|
|
1194
1259
|
```tsx
|
|
1195
1260
|
import { useRestoreScroll, useLoaderState } from 'clear-react-router';
|
|
1196
1261
|
|
|
1197
1262
|
const SlowTable = () => {
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
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
|
+
);
|
|
1206
1271
|
};
|
|
1207
1272
|
```
|
|
1208
1273
|
|
|
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
|
|
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:
|
|
1210
1275
|
|
|
1211
1276
|
```tsx
|
|
1212
1277
|
const Dashboard = () => {
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
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 />;
|
|
1225
1290
|
};
|
|
1226
1291
|
```
|
|
1227
1292
|
|
|
1228
1293
|
Details worth knowing:
|
|
1229
1294
|
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
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.
|
|
1234
1299
|
|
|
1235
1300
|
### `useRouteStatus()`
|
|
1236
1301
|
|
|
@@ -1249,13 +1314,13 @@ To render your own loading indicator (for example next to a link while its targe
|
|
|
1249
1314
|
import { Link, useRouteStatus } from 'clear-react-router';
|
|
1250
1315
|
|
|
1251
1316
|
const NavLink = ({ to, children }: { to: string; children: ReactNode }) => {
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
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
|
+
);
|
|
1259
1324
|
};
|
|
1260
1325
|
```
|
|
1261
1326
|
|
|
@@ -1266,6 +1331,7 @@ For per-link pending styling without custom components, `pendingClassName` and t
|
|
|
1266
1331
|
### `useRouterContext()`
|
|
1267
1332
|
|
|
1268
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
|
+
|
|
1269
1335
|
```tsx
|
|
1270
1336
|
const { setContext, context } = useRouterContext();
|
|
1271
1337
|
const loginHandler = () => setContext({ ...context, user: { name: 'John' } });
|
|
@@ -1279,34 +1345,35 @@ Returns an object for working with URL query parameters. Supports reading and se
|
|
|
1279
1345
|
import { useSearchParams } from 'clear-react-router';
|
|
1280
1346
|
|
|
1281
1347
|
function ProductFilter() {
|
|
1282
|
-
|
|
1348
|
+
const { searchParams, getSearchParams, setSearchParams } = useSearchParams();
|
|
1283
1349
|
|
|
1284
|
-
|
|
1285
|
-
|
|
1350
|
+
// Get a single value or array
|
|
1351
|
+
const brand = getSearchParams('brand'); // 'nike' | ['nike', 'reebok'] | ''
|
|
1286
1352
|
|
|
1287
|
-
|
|
1288
|
-
|
|
1353
|
+
// Set a single value
|
|
1354
|
+
setSearchParams('brand', 'nike'); // ?brand=nike
|
|
1289
1355
|
|
|
1290
|
-
|
|
1291
|
-
|
|
1356
|
+
// Set multiple values (array)
|
|
1357
|
+
setSearchParams('brand', ['nike', 'reebok']); // ?brand=nike&brand=reebok
|
|
1292
1358
|
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1359
|
+
// Functional update (preserves other params)
|
|
1360
|
+
setSearchParams(prev => {
|
|
1361
|
+
prev.set('page', '2');
|
|
1362
|
+
prev.append('color', 'red');
|
|
1363
|
+
return prev;
|
|
1364
|
+
});
|
|
1299
1365
|
|
|
1300
|
-
|
|
1301
|
-
|
|
1366
|
+
// Direct access to URLSearchParams
|
|
1367
|
+
const allParams = searchParams.toString(); // "brand=nike&brand=reebok&page=2"
|
|
1302
1368
|
}
|
|
1303
1369
|
```
|
|
1370
|
+
|
|
1304
1371
|
**Returns:**
|
|
1305
1372
|
|
|
1306
|
-
| Property
|
|
1307
|
-
|
|
1308
|
-
| `searchParams`
|
|
1309
|
-
| `getSearchParams` | `(key: string) => string \| string[]`
|
|
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 |
|
|
1310
1377
|
| `setSearchParams` | `(param: string, value: string \| string[]) => void` `or` `(updater: (prev: URLSearchParams) => URLSearchParams) => void` | Update query parameters. Supports single values, arrays, or functional updates |
|
|
1311
1378
|
|
|
1312
1379
|
**Key features:**
|
|
@@ -1321,23 +1388,23 @@ function ProductFilter() {
|
|
|
1321
1388
|
|
|
1322
1389
|
```tsx
|
|
1323
1390
|
function ProductFilter() {
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
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
|
+
};
|
|
1341
1408
|
}
|
|
1342
1409
|
```
|
|
1343
1410
|
|
|
@@ -1346,6 +1413,7 @@ function ProductFilter() {
|
|
|
1346
1413
|
## Lazy Loading
|
|
1347
1414
|
|
|
1348
1415
|
Clear Router supports code-splitting out of the box. Simply wrap dynamic import into a library's `lazy` function:
|
|
1416
|
+
|
|
1349
1417
|
```tsx
|
|
1350
1418
|
import { lazy } from 'clear-react-router';
|
|
1351
1419
|
|
|
@@ -1375,14 +1443,14 @@ fast data while slow data streams in separately:
|
|
|
1375
1443
|
|
|
1376
1444
|
```tsx
|
|
1377
1445
|
const Slow = () => {
|
|
1378
|
-
|
|
1379
|
-
|
|
1446
|
+
const { data } = useLoaderState<{ slow: Promise<string> }>();
|
|
1447
|
+
return use(data.slow);
|
|
1380
1448
|
};
|
|
1381
1449
|
|
|
1382
1450
|
const About = () => (
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1451
|
+
<Suspense fallback={<Skeleton />}>
|
|
1452
|
+
<Slow />
|
|
1453
|
+
</Suspense>
|
|
1386
1454
|
);
|
|
1387
1455
|
```
|
|
1388
1456
|
|
|
@@ -1411,6 +1479,7 @@ View Transitions API requires modern browsers:
|
|
|
1411
1479
|
For older browsers, the router gracefully falls back to regular navigation without animation.
|
|
1412
1480
|
|
|
1413
1481
|
## Requirements
|
|
1482
|
+
|
|
1414
1483
|
- React 16.8+ (for React.lazy and Suspense)
|
|
1415
1484
|
- Use `default` export for your lazy-loaded components
|
|
1416
1485
|
|
|
@@ -1425,5 +1494,6 @@ LRU eviction with a tiny cache, gcTime cleanup, an invalidation lab, a live cach
|
|
|
1425
1494
|
in-browser server.
|
|
1426
1495
|
Open devtools and click around.
|
|
1427
1496
|
|
|
1428
|
-
|
|
1429
|
-
|
|
1497
|
+
## License
|
|
1498
|
+
|
|
1499
|
+
MIT
|