clear-react-router 2.5.7 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1385,32 +1385,17 @@ function ProductFilter() {
1385
1385
 
1386
1386
  > **Note:** `getSearchParams` returns `string` for single values, `string[]` for multiple values, and `''` if the key is not found.
1387
1387
 
1388
- > **Note:** `setSearchParams` replaces the current history entry in place and does **not** run the route `loader` again. If the loader depends on query params, opt in explicitly:
1388
+ > **Note:** `setSearchParams` performs a full navigation to the same pathname with the new query:
1389
+ > it pushes a history entry and runs the route `loader` again with the updated `searchParams`.
1390
+ > Loader data is cached per `pathname + search`, so returning to a previously visited combination
1391
+ > of parameters is instant. To revalidate the current parameters without adding a history entry,
1392
+ > use `useInvalidate()`:
1389
1393
 
1390
1394
  ```tsx
1391
- function ProductFilter() {
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
- };
1409
- }
1395
+ const invalidate = useInvalidate();
1396
+ await invalidate(); // reruns the loader, keeps the history entry
1410
1397
  ```
1411
1398
 
1412
- `invalidate()` revalidates every cached search variant of the pathname; only the variant matching the active `pathname + search` updates the current loader state.
1413
-
1414
1399
  ## Lazy Loading
1415
1400
 
1416
1401
  Clear Router supports code-splitting out of the box. Simply wrap dynamic import into a library's `lazy` function:
package/dist/index.js CHANGED
@@ -334,6 +334,7 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
334
334
  routeItem,
335
335
  location,
336
336
  status: "optimistic",
337
+ keepsPreviousData: false,
337
338
  ...currentLoaderState && { loaderState: currentLoaderState }
338
339
  }));
339
340
  });
@@ -342,7 +343,8 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
342
343
  ...prevState,
343
344
  routeItem,
344
345
  location,
345
- status: "pending"
346
+ status: "pending",
347
+ keepsPreviousData: !!routeItem?.keepPreviousData && prevState.routeItem === routeItem && prevState.loaderState.data !== void 0 && prevState.status !== "error"
346
348
  })));
347
349
  const isOptimisticHit = (routeItem, path) => !!routeItem?.optimistic && loaderMap.has(path);
348
350
  const needsLoading = (routeItem, path) => !!routeItem?.loader && !isCacheItemFresh(path);
@@ -456,7 +458,7 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
456
458
  error: null,
457
459
  beforeLoadError
458
460
  } : await loader(nextItem, nextLocation, seq);
459
- if (seq !== navigationSeq) return;
461
+ if (seq !== navigationSeq || result === null) return;
460
462
  const loaderStateValue = {
461
463
  data: result?.data,
462
464
  loaderError: result?.error ?? null,
@@ -621,10 +623,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
621
623
  };
622
624
  const revalidateCache = async ({ routeItem, location, signal, force, reason }, retried = 0) => {
623
625
  if (!routeItem?.loader) return;
624
- if (signal?.aborted) return {
625
- data: null,
626
- error: null
627
- };
626
+ if (signal?.aborted) return null;
628
627
  const externalCache = routeItem.externalCache ?? routerConfig.defaultExternalCache;
629
628
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
630
629
  const { pathname, search = "" } = location;
@@ -674,10 +673,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
674
673
  signal: effectiveSignal,
675
674
  attempt: retried + 1
676
675
  });
677
- if (!isOwner() || effectiveSignal.aborted) return {
678
- data: null,
679
- error: null
680
- };
676
+ if (!isOwner() || effectiveSignal.aborted) return null;
681
677
  const resolvedStaleTime = routeItem.staleTime ?? routerConfig.defaultStaleTime ?? 0;
682
678
  loaderMap.set(path, {
683
679
  state: {
@@ -696,10 +692,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
696
692
  error: null
697
693
  };
698
694
  } catch (error) {
699
- if (effectiveSignal.aborted || !isOwner()) return {
700
- data: null,
701
- error: null
702
- };
695
+ if (effectiveSignal.aborted || !isOwner()) return null;
703
696
  const retry = getRetry(routeItem);
704
697
  if (retry && retry.count > retried) {
705
698
  if (isOwner()) {
@@ -708,7 +701,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
708
701
  flightReasons.delete(path);
709
702
  }
710
703
  if (retry.delay) await sleep(retry.delay);
711
- return revalidateCache({
704
+ return await revalidateCache({
712
705
  routeItem,
713
706
  location,
714
707
  signal,
@@ -914,11 +907,7 @@ var createRouterInstance = (synchronizer) => {
914
907
  const state = routerState.routeDataState;
915
908
  return synchronizer(state.subscribe, () => callback(state.getState()));
916
909
  },
917
- useCacheSnapshot: () => useGlobalState(routerState.cacheSnapshotState, synchronizer)[0],
918
- useSetLocation: () => (location) => routerState.routeDataState.setState((prevState) => ({
919
- ...prevState,
920
- location
921
- }))
910
+ useCacheSnapshot: () => useGlobalState(routerState.cacheSnapshotState, synchronizer)[0]
922
911
  }
923
912
  };
924
913
  };
@@ -1051,8 +1040,9 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
1051
1040
  const routeItem = useRouteDataSelector((state) => state.routeItem);
1052
1041
  const location = useRouteDataSelector((state) => state.location);
1053
1042
  const status = useRouteDataSelector((state) => state.status);
1043
+ const keepsPreviousData = useRouteDataSelector((state) => state.keepsPreviousData ?? false);
1054
1044
  const isError = status === "error";
1055
- const isLoading = status === "pending";
1045
+ const loadingContent = status === "pending" && !isError && !keepsPreviousData;
1056
1046
  useSetRouterConfig({
1057
1047
  routes,
1058
1048
  isAnimated,
@@ -1075,7 +1065,6 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
1075
1065
  useRestoreRouteScroll(defaultScrollRestorationBehavior);
1076
1066
  useReload();
1077
1067
  useNavigation();
1078
- const loadingContent = isLoading && !isError;
1079
1068
  if (!routeItem) return renderElement(loadingContent ? defaultLoaderFallback : void 0);
1080
1069
  const content = loadingContent ? renderElement(routeItem.loaderFallback || defaultLoaderFallback) : isError ? renderElement(routeItem.errorElement || defaultErrorElement) : /* @__PURE__ */ jsx(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname);
1081
1070
  return routeItem.layouts.reduceRight((acc, Layout) => {
@@ -1312,10 +1301,10 @@ var useLatest = (value) => {
1312
1301
  return ref;
1313
1302
  };
1314
1303
  var useSearchParams = () => {
1315
- const { useRouteDataSelector, useSetLocation } = router.hooks;
1304
+ const { useRouteDataSelector, useNavigate } = router.hooks;
1316
1305
  const location = useRouteDataSelector((state) => state.location);
1317
1306
  const { search = window.location.search } = location;
1318
- const setLocation = useSetLocation();
1307
+ const navigate = useNavigate();
1319
1308
  const searchRef = useLatest(search);
1320
1309
  const searchParams = useMemo(() => new URLSearchParams(search), [search]);
1321
1310
  const getSearchParams = useCallback((param) => {
@@ -1325,12 +1314,12 @@ var useSearchParams = () => {
1325
1314
  const navigateWithSearchParams = useCallback((params) => {
1326
1315
  const newSearch = params.toString();
1327
1316
  const search = newSearch ? `?${newSearch}` : "";
1328
- history.replaceState(history.state, "", (location ?? window.location).pathname + search);
1329
- setLocation({
1317
+ if (search === (location.search ?? "")) return;
1318
+ navigate({
1330
1319
  ...location,
1331
1320
  search
1332
1321
  });
1333
- }, [location, setLocation]);
1322
+ }, [location, navigate]);
1334
1323
  return {
1335
1324
  searchParams,
1336
1325
  getSearchParams,
package/dist/types.d.ts CHANGED
@@ -42,6 +42,9 @@ export type ClientRouteItem = {
42
42
  externalCache?: boolean;
43
43
  gcTime?: number;
44
44
  optimistic?: boolean;
45
+ /** While pending, keep the previous loader data on screen instead of the fallback.
46
+ * Applies only when the pending navigation targets the same element and previous data exists. */
47
+ keepPreviousData?: boolean;
45
48
  pollingInterval?: number;
46
49
  retry?: Retry;
47
50
  minLoaderDuration?: number;
@@ -90,6 +93,8 @@ export type RouteData = {
90
93
  routeItem: RouteItem | undefined;
91
94
  status: Status;
92
95
  loaderState: LoaderState;
96
+ /** Pending keeps the previous loader data on screen (routeItem.keepPreviousData). */
97
+ keepsPreviousData?: boolean;
93
98
  };
94
99
  type ObjectRetry = {
95
100
  count: number;
@@ -147,7 +152,7 @@ export type LoadingPromise = Promise<{
147
152
  } | {
148
153
  data: null;
149
154
  error: unknown;
150
- } | undefined>;
155
+ } | null | undefined>;
151
156
  export type ScrollMap = Record<string, [string, number][]>;
152
157
  export type RouterState = {
153
158
  routeDataState: Store<RouteData>;
@@ -183,7 +188,6 @@ export type RouterType = {
183
188
  useScrollRestoration(restorationBehavior: ScrollRestorationBehavior): () => void;
184
189
  useRouteDataSelector<T>(callback: (arg: RouteData) => T): T;
185
190
  useCacheSnapshot(): CacheSnapshot;
186
- useSetLocation(): (location: Location) => void;
187
191
  };
188
192
  };
189
193
  export type InvalidateOptions = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.5.7",
3
+ "version": "2.6.0",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {
@@ -36,7 +36,8 @@
36
36
  "react-dom": ">=16.8.0"
37
37
  },
38
38
  "files": [
39
- "dist"
39
+ "dist",
40
+ "skills"
40
41
  ],
41
42
  "license": "MIT",
42
43
  "type": "module",
@@ -0,0 +1,82 @@
1
+ ---
2
+ name: getting-started
3
+ description: Set up and build with clear-react-router — provider-free routing for React SPAs: nested routes, loaders with per-path+search caching, URL search state, blocking, invalidation and prefetch. Route any AI task about this library here first.
4
+ metadata:
5
+ type: framework
6
+ library: 'clear-react-router'
7
+ framework: react
8
+ sources:
9
+ - https://github.com/AndrewBubnov/clear-react-router/blob/master/README.md
10
+ - https://github.com/AndrewBubnov/clear-react-router/blob/master/src/playground/routes.tsx
11
+ - https://github.com/AndrewBubnov/clear-react-router/blob/master/src/e2e-demo.tsx
12
+ ---
13
+
14
+ # clear-react-router
15
+
16
+ A lightweight, provider-free routing library for client-side React SPAs. There is no
17
+ provider and no React context: all state lives in a global store, components subscribe
18
+ through hooks. One `<Router>` at the root, hooks anywhere.
19
+
20
+ ## Setup
21
+
22
+ ```tsx
23
+ import { Router, createRouter, lazy, useLoaderState, Link } from 'clear-react-router';
24
+
25
+ const routes = createRouter([
26
+ {
27
+ path: '/users',
28
+ element: lazy(() => import('./UsersPage')),
29
+ loader: ({ params, searchParams, signal }) => fetchUsers(params, searchParams, signal),
30
+ staleTime: 10_000, // cache entry lives this long
31
+ loaderFallback: <PageSkeleton />, // rendered while status is 'pending'
32
+ children: [{ path: '/:userId', element: <UserPage /> }], // paths are relative
33
+ },
34
+ { path: '*', element: <NotFound /> }, // catch-all, keep it last
35
+ ]);
36
+
37
+ createRoot(root).render(<Router routes={routes} />);
38
+ ```
39
+
40
+ ```tsx
41
+ // Any component
42
+ const { data, loaderError, beforeLoadError } = useLoaderState<User[]>();
43
+ const navigate = useNavigate();
44
+ navigate({ pathname: '/users', search: '?sort=asc' });
45
+ ```
46
+
47
+ ## Essential constraints
48
+
49
+ - **No context, no provider.** Hooks read a global singleton; render `<Router>` once.
50
+ - **The loader is the data owner.** `loader` receives `{ params, searchParams, context,
51
+ setContext, location, signal, attempt }` and returns anything serializable. Its result
52
+ is cached per **`pathname + search`** — a different query string is a different entry.
53
+ - **`beforeLoad` is for guards, not data.** Redirect via `redirect(location)` in its args;
54
+ a thrown/rejected error lands in `beforeLoadError` and renders `errorElement`.
55
+ - **Search params are navigations.** `setSearchParams` performs a full navigation: it
56
+ pushes a history entry and re-runs the loader for the new `pathname + search`. Never
57
+ bypass it by writing to the store or calling `history.*` directly.
58
+ - **Render during loading is a three-slot pipeline** (route-level opt-ins, see below):
59
+ `optimistic` → `keepPreviousData` → `loaderFallback`. Errors always replace content
60
+ with `errorElement`.
61
+ - **Routes without a `loader` never have loader data.** Such routes commit
62
+ `status: 'active'` with `data === undefined`; an element there must not read `data`.
63
+ - **Aborts are automatic.** Each navigation has one signal, passed to the loader;
64
+ superseding a navigation cancels the previous flight. Do not create your own
65
+ `AbortController` for loaders.
66
+
67
+ ## Load by task
68
+
69
+ - Route config, nested routes, layouts, params, catch-all, lazy elements →
70
+ [routes and loaders](references/routes-and-loaders.md)
71
+ - Caching, `staleTime`/`gcTime`, loading UX (`optimistic`, `keepPreviousData`,
72
+ `loaderFallback`, retry, polling) → [loaders and caching](references/routes-and-loaders.md)
73
+ - URL query state, filters/sort/pagination tables, multi-value params →
74
+ [search params as state](references/search-params-state.md)
75
+ - Navigation, blockers, invalidation, prefetch, actions →
76
+ [navigation and blocking](references/navigation-blocking-invalidation.md)
77
+
78
+ ## API discovery
79
+
80
+ Inspect `src/clear-router/index.ts` (the only public entry point), then `src/clear-router/types.ts`
81
+ for `RouteItem` and hook signatures. The playground (`src/playground/routes.tsx`) shows every
82
+ feature wired end-to-end against a fake in-browser server.
@@ -0,0 +1,73 @@
1
+ # Navigation, blocking, invalidation, actions
2
+
3
+ ## useNavigate
4
+
5
+ ```tsx
6
+ const navigate = useNavigate();
7
+ navigate('/users/42'); // string ('-1' = history back)
8
+ navigate({ pathname: '/users', search: '?sort=asc' });
9
+ navigate({ path: '/users/:userId', params: { userId: '42' } }); // typed
10
+ navigate(-1); // browser back
11
+ ```
12
+
13
+ `search` carries its leading `?` everywhere downstream (Location, cache keys). Same
14
+ `path + search` navigations are skipped: nothing is pushed and no loader runs.
15
+
16
+ ## Blocking (useBlocker)
17
+
18
+ ```tsx
19
+ const { state, process, reset } = useBlocker(() => dirty);
20
+ // state: 'unblocked' → 'charged' (armed) → 'blocked' (a navigation was intercepted)
21
+ ```
22
+
23
+ The callback receives `{ location, nextLocation, context }` and returns whether navigation
24
+ should be blocked — re-evaluated on every render, so plain booleans work. When armed,
25
+ the next navigation (links, programmatic, browser Back) suspends; show a dialog on
26
+ `state === 'blocked'`, then `process()` to continue to the target or `reset()` to stay
27
+ armed. Use for dirty forms.
28
+
29
+ ## Invalidation (useInvalidate)
30
+
31
+ ```tsx
32
+ const invalidate = useInvalidate();
33
+ await invalidate(); // current route
34
+ await invalidate('/users'); // concrete path
35
+ await invalidate('/users/:id'); // pattern → every matching cache entry
36
+ await invalidate('/users', { withChildren: true });
37
+ await invalidate(undefined, { staleOnly: true }); // mark stale, refetch lazily
38
+ ```
39
+
40
+ Invalidation deletes the cache entry and re-runs the loader; only the result matching
41
+ the currently active `pathname + search` updates the on-screen loader state. Use for
42
+ post-mutation refreshes; `useSubmitAction` triggers dependent invalidations
43
+ automatically.
44
+
45
+ ## Prefetch
46
+
47
+ Router prop `defaultPrefetch: 'hover' | 'viewport' | 'none'` (device-aware default).
48
+ `<Link>` options: `prefetch` (per-link override), `hoverPrefetchDelay` (ms),
49
+ `preloadElement` runs the lazy import early. Concurrency: 4 desktop / 2 mobile.
50
+ A prefetch is never a superseder: it rides an already running flight for the same key
51
+ and never aborts it — safe to hover aggressively.
52
+
53
+ ## Actions (mutations)
54
+
55
+ ```tsx
56
+ // Route config
57
+ actions: ({ params, context, setContext, location }) => ({
58
+ saveNote: async data => { ... },
59
+ }),
60
+ // Component — one hook per action
61
+ const { submit, isSubmitting, data, error } = useSubmitAction('saveNote');
62
+ submit(payload); // runs the action, then invalidates affected cache
63
+ const saveNote = useAction('saveNote', { onSuccess, onError }); // raw call
64
+ ```
65
+
66
+ Actions are route-owned mutations; after a successful action the affected loader data is
67
+ invalidated so the UI reflects the mutation without manual refreshes.
68
+
69
+ ## Scroll restoration
70
+
71
+ `scrollRestoration: true` (window) or an array of container ids (`'feed'`, `'gallery'`).
72
+ Router prop `defaultScrollRestorationBehavior: 'auto' | 'smooth'`. Paired with the
73
+ browser history so Back restores the scroll position of the previous entry.
@@ -0,0 +1,83 @@
1
+ # Routes and loaders
2
+
3
+ ## Route shape
4
+
5
+ ```tsx
6
+ {
7
+ path: '/users', // children are appended: '/users/:userId'
8
+ element: <UsersPage />, // or lazy(() => import('./UsersPage'))
9
+ loader: fetchUsers, // optional; data cached per pathname + search
10
+ beforeLoad: async ({ redirect, signal }) => { ... }, // guards, redirects
11
+ afterLoad: async ({ params, context }) => { ... }, // runs after every successful navigation
12
+ retry: { count: 3, delay: 400 },// retry failed loader attempts (or a number = count)
13
+ staleTime: 10_000, // ms before the cache entry goes stale
14
+ gcTime: 30_000, // idle entry is evicted after this
15
+ optimistic: true, // instant cache hit for revisited keys
16
+ keepPreviousData: true, // keep previous data on screen during pending
17
+ loaderFallback: <Skeleton />, // rendered while pending (no keepPreviousData)
18
+ errorElement: lazy(() => import('./ErrorView')), // on beforeLoad or loader failure
19
+ pollingInterval: 3000, // re-run the loader while the route is active
20
+ externalCache: false, // opt out of router cache freshness for this route
21
+ scrollRestoration: 'feed', // restore window or named container scroll
22
+ children: [ ... ], // nested routes; child paths are relative
23
+ }
24
+ ```
25
+
26
+ Layouts: `layout: Component` (or `layouts: [Outer, Inner]` on a parent route) wraps the
27
+ section and receives the rendered children as `children` — no Outlet component; layouts
28
+ stack outermost-first and are inherited by descendants. The catch-all
29
+ `{ path: '*', element: <NotFound /> }` matches any depth; keep it last.
30
+
31
+ ## Loader args
32
+
33
+ ```ts
34
+ loader: ({ params, searchParams, context, setContext, location, signal, attempt }) => Promise<unknown>
35
+ ```
36
+
37
+ - `params` — path params (`/users/:userId` → `{ userId }`).
38
+ - `searchParams` — plain object built from the URL query (multi-value keys collapse to
39
+ the last value; for multi-value reads use `location.search` directly).
40
+ - `signal` — abort signal of the owning navigation; pass it to `fetch`.
41
+ - `attempt` — 1-based retry attempt number.
42
+ - `setContext` — write shared context during load (React-friendly: batched updates).
43
+
44
+ ## Caching
45
+
46
+ - Key: `pathname + search`. Same path with a different query = a different entry.
47
+ - Fresh within `staleTime` (route-level) or `defaultStaleTime` (Router prop) → the loader
48
+ does not re-run; revisits are instant.
49
+ - Router-level defaults: `defaultStaleTime`, `defaultRetry`, `defaultMinLoaderDuration`
50
+ (minimum pending time — prevents skeleton flashing on fast loaders), `maxCacheSize`
51
+ (LRU-style eviction), `gcTime` on routes for idle eviction.
52
+ - `revalidateOnFocus` / `revalidateOnReconnect` revalidate the active route in the
53
+ background.
54
+
55
+ ## Loading UX pipeline
56
+
57
+ Deciding what to render while a navigation loads, in priority order:
58
+
59
+ | Condition | Rendered | Status |
60
+ | --- | --- | --- |
61
+ | Cache has the exact `path + search` key (`optimistic: true`) | cached data of the **new** key, revalidated in background | `optimistic` |
62
+ | `keepPreviousData: true`, same element, previous data exists | previous data stays on screen | `pending` |
63
+ | otherwise | `loaderFallback` (or `defaultLoaderFallback`) | `pending` |
64
+ | loader or beforeLoad failed | `errorElement` | `error` |
65
+
66
+ `keepPreviousData` applies only when the pending navigation targets the same element
67
+ (identity from the routes config) and the previous `loaderState` has data — e.g. changing
68
+ table filters. A failed loader always replaces kept data with `errorElement`.
69
+
70
+ A pending status is still reported by `useRouteStatus()` — use it for badges instead of
71
+ blocking the table (an "updating…" chip that shifts layout is an anti-pattern here).
72
+
73
+ ## Reading data
74
+
75
+ ```tsx
76
+ const { data, loaderError, beforeLoadError } = useLoaderState<T>();
77
+ const status = useRouteStatus(); // 'idle' | 'pending' | 'active' | 'optimistic' | 'error'
78
+ ```
79
+
80
+ `data` is committed together with its status: during `pending` the store keeps the
81
+ previous route's `loaderState` until the new one is committed. Do not assume `data`
82
+ belongs to the current URL unless `status` is `active`/`optimistic` (or the route
83
+ committed with `keepPreviousData` — then the mismatch is intentional and flagged).
@@ -0,0 +1,57 @@
1
+ # Search params as URL state
2
+
3
+ `useSearchParams()` treats the query string as application state owned by the router.
4
+ This is the pattern for table filters, sorting and pagination.
5
+
6
+ ```tsx
7
+ const { searchParams, getSearchParams, setSearchParams } = useSearchParams();
8
+
9
+ searchParams.toString(); // raw URLSearchParams
10
+ getSearchParams('brand'); // 'nike' | ['nike', 'reebok'] | ''
11
+ setSearchParams('page', '2'); // single value
12
+ setSearchParams('brand', ['nike', 'reebok']); // multi-value (appends)
13
+ setSearchParams(prev => { prev.set('page', '2'); return prev; }); // functional update
14
+ ```
15
+
16
+ ## Semantics — read this before writing UI code
17
+
18
+ - **`setSearchParams` is a full navigation.** It pushes a history entry and re-runs the
19
+ route `loader` with the new `pathname + search`. This is the router's whole model:
20
+ every query combination is a first-class, independently cached navigation.
21
+ - **Cache is per `pathname + search`.** Toggling sort A→B→A reuses the cache for A on the
22
+ second visit (within `staleTime`) — instant, no loader call. Pair this with
23
+ `keepPreviousData: true` so unseen combinations keep the current rows on screen.
24
+ - **Identical parameters are a no-op** (no duplicate history entry, no loader call).
25
+ - **Back/Forward walks the filter history**, and every entry has its own cached data.
26
+ - Blockers and `beforeLoad` see search-param changes like any navigation.
27
+
28
+ ## Real case: a server-driven table
29
+
30
+ The playground's search page (`src/playground/SearchPage.tsx`) is the reference
31
+ implementation. Shape to copy:
32
+
33
+ - Controls (`setSearchParams`) write the URL: `q`, `sort`, `dir`, `page`, multi-value `brand`.
34
+ - The loader reads `location.search` and returns the already filtered/sorted/paginated
35
+ page of rows (`manual*` TanStack Table mode; the table instance is a pure renderer).
36
+ - Route: `loader` + `staleTime` + `keepPreviousData: true` + `loaderFallback`.
37
+
38
+ ```tsx
39
+ // Server-side multi-value filter: read the raw search, not the collapsed object.
40
+ loader: ({ location }) => {
41
+ const brands = new URLSearchParams(location.search).getAll('brand');
42
+ return fetchRows({ brands, search: location.search });
43
+ };
44
+ ```
45
+
46
+ ## Common mistakes
47
+
48
+ - **Debouncing per keystroke.** Each `setSearchParams` is a navigation; commit on
49
+ Enter/blur or debounce deliberately. Typing 'q' letter-by-letter creates a history
50
+ entry and a loader flight per key.
51
+ - **Setting state from the loader back into params.** The URL is the single source of
52
+ truth for query state; components read, they don't mirror.
53
+ - **Forgetting page reset.** Changing a filter while on page 4 leaves `page=4` — reset
54
+ the page param whenever the result set changes shape.
55
+ - **Writing `history.replaceState` directly** to "just update the search" — this
56
+ desynchronizes the router store from the URL (loader never re-runs, blockers bypassed).
57
+ Always go through `setSearchParams` / `navigate`.