clear-react-router 2.2.0 → 2.2.1

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
@@ -81,6 +81,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
81
81
  | `optimistic` | `boolean \| undefined` | Instant navigation using stale data while fresh data is loaded in the background |
82
82
  | `errorElement` | `ReactElement \| () => ReactElement` | Error fallback for the route. Overrides the global `defaultErrorElement` set in `Router` |
83
83
  | `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, cached data never expires |
84
+ | `gcTime` | `number \| undefined` | How long, in milliseconds, an unused cache entry is kept in memory after you navigate away, before it's garbage-collected |
84
85
  | `actions` | `({ params, context, invalidate, setContext }) => Record<string, (formData: FormData) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. Actions receive `FormData`, can update context via `setContext`, and can invalidate cached loader data using the router-provided `invalidate` |
85
86
  | `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active |
86
87
  | `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` |
@@ -110,9 +111,11 @@ Before load arguments (see [`redirect`](#redirect) for details on programmatic r
110
111
  `loader` additionally receives:
111
112
  ```ts
112
113
  {
113
- signal: AbortSignal; // Aborted if a newer navigation supersedes this one — pass to fetch() to cancel in-flight requests
114
+ signal: AbortSignal; // Aborted if a newer navigation supersedes this one — pass to fetch() to cancel in-flight requests
114
115
  }
115
116
  ```
117
+ > **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.
118
+ 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.
116
119
 
117
120
  ### `Link`
118
121
 
@@ -541,7 +544,7 @@ const App = () => <Router routes={routes} errorBoundary={ErrorBoundary} />
541
544
  Returns a function to navigate programmatically. Accepts a string (pathname, optionally with a `?query`), a `NavigationLocation` object, or `-1` to go back.
542
545
 
543
546
  ```tsx
544
- type NavigationLocation = { pathname: string; search?: string | Record<string, string | number | boolean | null | undefined>; state?: unknown }
547
+ type NavigationLocation = { pathname: string; search?: string | Record<string, string | number | boolean | null | undefined>; state?: unknown }
545
548
 
546
549
  const navigate = useNavigate();
547
550
 
@@ -870,6 +873,42 @@ import { lazy } from 'clear-react-router';
870
873
  fallback: () => <div>Loading...</div>,
871
874
  }
872
875
  ```
876
+
877
+ ## Deferred data (React 19 `use()`)
878
+
879
+ `loader` can return a value containing unresolved promises — the router doesn't await
880
+ anything beyond what your `loader` itself awaits. This lets you unblock navigation on
881
+ fast data while slow data streams in separately:
882
+
883
+ ```tsx
884
+ {
885
+ path: '/about',
886
+ loader: async () => {
887
+ const fast = await fetchFast();
888
+ const slow = fetchSlow(); // not awaited — passed through as a promise
889
+ return { fast, slow };
890
+ },
891
+ }
892
+ ```
893
+
894
+ ```tsx
895
+ const Slow = () => {
896
+ const { data } = useLoaderState<{ slow: Promise<string> }>();
897
+ return use(data.slow);
898
+ };
899
+
900
+ const About = () => (
901
+ <Suspense fallback={<Skeleton />}>
902
+ <Slow />
903
+ </Suspense>
904
+ );
905
+ ```
906
+
907
+ > Wrap deferred parts in their own `ErrorBoundary` — a rejected promise passed to `use()`
908
+ > is not caught by the route's `errorElement`. Also set `staleTime` generously enough to
909
+ > outlast your slowest deferred request, or a fast repeat visit may trigger a redundant
910
+ > refetch while the previous one is still resolving.
911
+
873
912
  ## Animations
874
913
 
875
914
  Clear Router supports smooth page transitions using the native View Transitions API. When animations are enabled, the router waits for all data to load before starting the transition, ensuring a jank-free experience.
package/dist/index.js CHANGED
@@ -30,16 +30,16 @@ var useGlobalState = ({ subscribe, getState, setState }) => {
30
30
  };
31
31
  //#endregion
32
32
  //#region utils/commitState.ts
33
- var createCommitState = ({ loaderStateRef, loaderState, routeItemDataState }) => (nextLocation, routeItem) => {
34
- const isError = loaderStateRef.value.loaderError || loaderStateRef.value.beforeLoadError;
33
+ var createCommitState = ({ loaderState, routeItemDataState }) => ({ routeItem, loaderStateValue, location }) => {
34
+ const isError = loaderStateValue.loaderError || loaderStateValue.beforeLoadError;
35
35
  routeItemDataState.setState({
36
36
  routeItem,
37
- location: nextLocation,
37
+ location,
38
38
  status: isError ? "error" : "active"
39
39
  });
40
- loaderState.setState(loaderStateRef.value);
41
- if ((nextLocation.search ? `${nextLocation.pathname}${nextLocation.search}` : nextLocation.pathname) === window.location.pathname + window.location.search) return;
42
- history.pushState(null, "", `${nextLocation.pathname}${nextLocation.search}`);
40
+ loaderState.setState(loaderStateValue);
41
+ if ((location.search ? `${location.pathname}${location.search}` : location.pathname) === window.location.pathname + window.location.search) return;
42
+ history.pushState(null, "", `${location.pathname}${location.search}`);
43
43
  };
44
44
  //#endregion
45
45
  //#region constants.ts
@@ -227,7 +227,7 @@ var createNavigate = (routerState, revalidateCache) => {
227
227
  let navigationSeq = 0;
228
228
  let interval = 0;
229
229
  let abortController = null;
230
- const { loaderState, loaderStateRef, contextState, loaderMap, routeItemDataState, scrollMapState, blockerState, blockedTargetState } = routerState;
230
+ const { loaderState, contextState, loaderMap, routeItemDataState, scrollMapState, blockerState, blockedTargetState } = routerState;
231
231
  const commitState = createCommitState(routerState);
232
232
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
233
233
  const createSignal = () => {
@@ -241,7 +241,6 @@ var createNavigate = (routerState, revalidateCache) => {
241
241
  setContext: contextState.setState
242
242
  });
243
243
  const routeResolve = (location) => {
244
- loaderStateRef.set(EMPTY_LOADER_STATE);
245
244
  const nextItem = findRoute(location.pathname, true);
246
245
  return {
247
246
  nextItem,
@@ -257,22 +256,33 @@ var createNavigate = (routerState, revalidateCache) => {
257
256
  redirect,
258
257
  ...getPartialLoaderArgs(contextState, nextLocation, routeItem)
259
258
  });
260
- loaderStateRef.set((prev) => ({
261
- ...prev,
262
- beforeLoadError: null
263
- }));
259
+ return null;
264
260
  } catch (error) {
265
- loaderStateRef.set((prev) => ({
266
- ...prev,
267
- beforeLoadError: error
268
- }));
261
+ return error;
269
262
  }
270
263
  };
271
- if (defaultBeforeLoad) await runBeforeLoad(defaultBeforeLoad);
272
- if (routeItem?.beforeLoad) await runBeforeLoad(routeItem?.beforeLoad);
264
+ let error = null;
265
+ if (defaultBeforeLoad) error = await runBeforeLoad(defaultBeforeLoad);
266
+ if (routeItem?.beforeLoad && !error) error = await runBeforeLoad(routeItem?.beforeLoad);
267
+ return error;
268
+ };
269
+ const createGcTimeout = () => {
270
+ const { routeItem, location } = routeItemDataState.getState();
271
+ if (!routeItem?.gcTime) return;
272
+ const path = `${location.pathname}${location.search}`;
273
+ const currentLoaderEntry = loaderMap.get(path);
274
+ if (!currentLoaderEntry) return;
275
+ if (currentLoaderEntry.gcTimeout) window.clearTimeout(currentLoaderEntry?.gcTimeout);
276
+ const gcTimeout = window.setTimeout(() => loaderMap.delete(path), routeItem.gcTime);
277
+ loaderMap.set(path, {
278
+ ...currentLoaderEntry,
279
+ gcTimeout
280
+ });
273
281
  };
274
- const prepareNavigation = (routeItem, location) => {
282
+ const prepareNavigation = (routeItem, location, hasError) => {
275
283
  updateScrollMap(routeItemDataState, scrollMapState);
284
+ createGcTimeout();
285
+ if (hasError) return;
276
286
  const path = getPath(location);
277
287
  if (routeItem?.optimistic && loaderMap.has(path)) {
278
288
  commitNavigation(() => routeItemDataState.setState({
@@ -301,7 +311,7 @@ var createNavigate = (routerState, revalidateCache) => {
301
311
  };
302
312
  const getLoaderDurationPromise = (routeItem, nextLocation) => {
303
313
  const minLoaderDuration = routeItem?.minLoaderDuration ?? routerConfig.defaultMinLoaderDuration ?? 0;
304
- return minLoaderDuration && !isCacheItemFresh(getPath(nextLocation)) ? sleep(minLoaderDuration) : Promise.resolve;
314
+ return minLoaderDuration && !isCacheItemFresh(getPath(nextLocation)) ? sleep(minLoaderDuration) : Promise.resolve();
305
315
  };
306
316
  const loader = async (routeItem, nextLocation, seq) => {
307
317
  if (!routeItem?.loader) return;
@@ -312,13 +322,9 @@ var createNavigate = (routerState, revalidateCache) => {
312
322
  location: nextLocation,
313
323
  signal
314
324
  }), getLoaderDurationPromise(routeItem, nextLocation)]);
315
- if (result) loaderStateRef.set((prev) => ({
316
- ...prev,
317
- data: result.data,
318
- loaderError: result.error
319
- }));
320
325
  if (seq !== navigationSeq) return;
321
326
  polling(routeItem, nextLocation);
327
+ return result;
322
328
  };
323
329
  const afterLoad = async (routeItem, params) => {
324
330
  const { defaultAfterLoad } = routerConfig;
@@ -339,6 +345,17 @@ var createNavigate = (routerState, revalidateCache) => {
339
345
  }
340
346
  return false;
341
347
  };
348
+ const clearCurrentGcTimeout = (routeItem, location) => {
349
+ const path = `${location.pathname}${location.search}`;
350
+ if (!routeItem?.gcTime) return;
351
+ const currentLoaderEntry = loaderMap.get(path);
352
+ if (!currentLoaderEntry?.gcTimeout) return;
353
+ window.clearTimeout(currentLoaderEntry.gcTimeout);
354
+ loaderMap.set(path, {
355
+ ...currentLoaderEntry,
356
+ gcTimeout: void 0
357
+ });
358
+ };
342
359
  const navigate = async (rawLocation) => {
343
360
  const nextLocation = {
344
361
  ...rawLocation,
@@ -348,12 +365,26 @@ var createNavigate = (routerState, revalidateCache) => {
348
365
  navigationSeq = navigationSeq + 1;
349
366
  const seq = navigationSeq;
350
367
  const { nextItem, params } = routeResolve(nextLocation);
351
- await beforeLoad(nextItem, nextLocation);
368
+ const beforeLoadError = await beforeLoad(nextItem, nextLocation);
352
369
  if (seq !== navigationSeq) return;
353
- prepareNavigation(nextItem, nextLocation);
354
- await loader(nextItem, nextLocation, seq);
370
+ prepareNavigation(nextItem, nextLocation, !!beforeLoadError);
371
+ const result = beforeLoadError ? {
372
+ data: null,
373
+ error: null,
374
+ beforeLoadError
375
+ } : await loader(nextItem, nextLocation, seq);
355
376
  if (seq !== navigationSeq) return;
356
- commitNavigation(() => commitState(nextLocation, nextItem));
377
+ const loaderStateValue = {
378
+ data: result?.data,
379
+ loaderError: result?.error ?? null,
380
+ beforeLoadError
381
+ };
382
+ commitNavigation(() => commitState({
383
+ location: nextLocation,
384
+ routeItem: nextItem,
385
+ loaderStateValue
386
+ }));
387
+ clearCurrentGcTimeout(nextItem, nextLocation);
357
388
  await afterLoad(nextItem, params);
358
389
  };
359
390
  return navigate;
@@ -524,20 +555,6 @@ var createRevalidateCache = (routerState) => {
524
555
  return revalidateCache;
525
556
  };
526
557
  //#endregion
527
- //#region cell.ts
528
- var Cell = class {
529
- constructor(_value) {
530
- _defineProperty(this, "_value", void 0);
531
- this._value = _value;
532
- }
533
- get value() {
534
- return this._value;
535
- }
536
- set(action) {
537
- this._value = typeof action === "function" ? action(this._value) : action;
538
- }
539
- };
540
- //#endregion
541
558
  //#region creators/createRouterInstance.ts
542
559
  var createRouterInstance = () => {
543
560
  const routerState = {
@@ -550,7 +567,6 @@ var createRouterInstance = () => {
550
567
  contextState: create({}),
551
568
  blockerState: create("unblocked"),
552
569
  loaderState: create(EMPTY_LOADER_STATE),
553
- loaderStateRef: new Cell(EMPTY_LOADER_STATE),
554
570
  blockedTargetState: create(null),
555
571
  loaderMap: /* @__PURE__ */ new Map(),
556
572
  loadingPromises: /* @__PURE__ */ new Map()
package/dist/types.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { ComponentType, type CSSProperties, Dispatch, MouseEvent, ReactElement, ReactNode, Ref, SetStateAction } from 'react';
2
2
  import { Store, useGlobalState } from './create';
3
- import { Cell } from './cell';
4
3
  export declare const LAZY_MARKER: unique symbol;
5
4
  export type LazyComponent = {
6
5
  readonly [LAZY_MARKER]: true;
@@ -31,6 +30,7 @@ export type ClientRouteItem = {
31
30
  fallback?: RenderElement;
32
31
  children?: ClientRouteItem[];
33
32
  staleTime?: number;
33
+ gcTime?: number;
34
34
  optimistic?: boolean;
35
35
  pollingInterval?: number;
36
36
  retry?: Retry;
@@ -106,6 +106,7 @@ export type LoaderStateItem = {
106
106
  state: LoaderState;
107
107
  timestamp: number;
108
108
  staleTime: number | undefined;
109
+ gcTimeout?: number;
109
110
  };
110
111
  export type LoadingPromise = Promise<{
111
112
  data: unknown;
@@ -122,7 +123,6 @@ export type RouterState = {
122
123
  blockerState: Store<BlockerState>;
123
124
  loaderState: Store<LoaderState>;
124
125
  blockedTargetState: Store<Location | null>;
125
- loaderStateRef: Cell<LoaderState>;
126
126
  loaderMap: Map<string, LoaderStateItem>;
127
127
  loadingPromises: Map<string, LoadingPromise>;
128
128
  };
@@ -1,2 +1,8 @@
1
- import { Location, RouteItem, RouterState } from '../types';
2
- export declare const createCommitState: ({ loaderStateRef, loaderState, routeItemDataState }: RouterState) => (nextLocation: Location, routeItem?: RouteItem) => void;
1
+ import { LoaderState, Location, RouteItem, RouterState } from '../types';
2
+ type CommitState = {
3
+ location: Location;
4
+ loaderStateValue: LoaderState;
5
+ routeItem?: RouteItem;
6
+ };
7
+ export declare const createCommitState: ({ loaderState, routeItemDataState }: RouterState) => ({ routeItem, loaderStateValue, location }: CommitState) => void;
8
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.2.0",
3
+ "version": "2.2.1",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {
package/dist/cell.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export declare class Cell<T> {
2
- private _value;
3
- constructor(_value: T);
4
- get value(): T;
5
- set(action: T | ((prev: T) => T)): void;
6
- }