npm-tanstack--react-router

Description
Modern and scalable routing for React applications with built-in data fetching, caching, and state management capabilities
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-tanstack--react-router@1.132.0

route-definition.md docs/

1
# Route Definition & Management
2
3
System for defining routes with type-safe parameters, search handling, data loading, and nested layouts. Supports both programmatic route creation and file-based routing patterns.
4
5
## Capabilities
6
7
### Route Creation
8
9
Create route instances with comprehensive configuration options including loaders, components, and validation.
10
11
```typescript { .api }
12
/**
13
* Create a route instance with configuration
14
* @param options - Route configuration options
15
* @returns Route instance
16
*/
17
function createRoute<TParentRoute extends AnyRoute = AnyRoute>(
18
options: RouteOptions<TParentRoute>
19
): Route<TParentRoute>;
20
21
interface RouteOptions<TParentRoute extends AnyRoute = AnyRoute> {
22
/** Function returning parent route */
23
getParentRoute?: () => TParentRoute;
24
/** Route path pattern */
25
path?: string;
26
/** Route ID for identification */
27
id?: string;
28
/** Route component */
29
component?: RouteComponent;
30
/** Error boundary component */
31
errorComponent?: ErrorRouteComponent;
32
/** Loading/pending component */
33
pendingComponent?: RouteComponent;
34
/** Not found component */
35
notFoundComponent?: NotFoundRouteComponent;
36
/** Route loader function */
37
loader?: RouteLoaderFn;
38
/** Route context function */
39
beforeLoad?: RouteContextFn;
40
/** Validation schema for search params */
41
validateSearch?: SearchValidator;
42
/** Transform search params */
43
search?: SearchTransform;
44
/** Static data */
45
staticData?: any;
46
/** Whether route should preload */
47
shouldReload?: boolean | ((match: RouteMatch) => boolean);
48
/** Stale time for route data */
49
staleTime?: number;
50
/** Garbage collection time */
51
gcTime?: number;
52
}
53
```
54
55
**Usage Examples:**
56
57
```typescript
58
import { createRoute, createRootRoute } from "@tanstack/react-router";
59
60
// Basic route
61
const homeRoute = createRoute({
62
getParentRoute: () => rootRoute,
63
path: "/",
64
component: () => <div>Home</div>,
65
});
66
67
// Route with parameters and loader
68
const postRoute = createRoute({
69
getParentRoute: () => rootRoute,
70
path: "/posts/$postId",
71
loader: async ({ params }) => {
72
const post = await fetchPost(params.postId);
73
return { post };
74
},
75
component: ({ useLoaderData }) => {
76
const { post } = useLoaderData();
77
return <div>{post.title}</div>;
78
},
79
});
80
81
// Route with search validation
82
const searchRoute = createRoute({
83
getParentRoute: () => rootRoute,
84
path: "/search",
85
validateSearch: (search) => ({
86
q: search.q || "",
87
page: Number(search.page) || 1,
88
}),
89
component: ({ useSearch }) => {
90
const { q, page } = useSearch();
91
return <SearchResults query={q} page={page} />;
92
},
93
});
94
```
95
96
### Root Route Creation
97
98
Create the root route that serves as the top-level route for the application.
99
100
```typescript { .api }
101
/**
102
* Create a root route
103
* @param options - Root route configuration options
104
* @returns Root route instance
105
*/
106
function createRootRoute<TRouterContext = unknown>(
107
options?: RootRouteOptions<TRouterContext>
108
): RootRoute<TRouterContext>;
109
110
/**
111
* Create a root route with typed context
112
* @returns Function to create root route with context
113
*/
114
function createRootRouteWithContext<TRouterContext>(): <TRouter extends AnyRouter = AnyRouter>(
115
options?: RootRouteOptions<TRouterContext>
116
) => RootRoute<TRouterContext>;
117
118
interface RootRouteOptions<TRouterContext = unknown> {
119
/** Root component */
120
component?: RouteComponent;
121
/** Root error component */
122
errorComponent?: ErrorRouteComponent;
123
/** Root pending component */
124
pendingComponent?: RouteComponent;
125
/** Root not found component */
126
notFoundComponent?: NotFoundRouteComponent;
127
/** Root loader function */
128
loader?: (opts: { context: TRouterContext }) => any;
129
/** Root context function */
130
beforeLoad?: (opts: { context: TRouterContext }) => any;
131
}
132
```
133
134
**Usage Examples:**
135
136
```typescript
137
import { createRootRoute, createRootRouteWithContext, Outlet } from "@tanstack/react-router";
138
139
// Basic root route
140
const rootRoute = createRootRoute({
141
component: () => (
142
<div>
143
<nav>Navigation</nav>
144
<Outlet />
145
</div>
146
),
147
});
148
149
// Root route with typed context
150
const createRootWithContext = createRootRouteWithContext<{
151
user: User;
152
theme: "light" | "dark";
153
}>();
154
155
const rootRoute = createRootWithContext({
156
component: () => <App />,
157
beforeLoad: ({ context }) => {
158
console.log("User:", context.user);
159
return { ...context };
160
},
161
});
162
```
163
164
### File-Based Routes
165
166
Create routes based on file system conventions with automatic type generation and file-system-based routing patterns.
167
168
```typescript { .api }
169
/**
170
* Create a file-based route with automatic type inference
171
* @param path - File path for type inference
172
* @returns Function to create route with file-based typing
173
*/
174
function createFileRoute<TFilePath extends keyof FileRoutesByPath>(
175
path?: TFilePath
176
): FileRoute<TFilePath>['createRoute'];
177
178
/**
179
* Create a lazy file route for code splitting
180
* @param id - File path used as route ID
181
* @returns Function to create lazy file route
182
*/
183
function createLazyFileRoute<TFilePath extends keyof FileRoutesByPath>(
184
id: TFilePath
185
): (opts: LazyRouteOptions) => LazyRoute<FileRoutesByPath[TFilePath]['preLoaderRoute']>;
186
187
/**
188
* File route loader function (deprecated - use loader in createFileRoute options)
189
* @param path - File path
190
* @returns Function to define typed loader
191
*/
192
function FileRouteLoader<TFilePath extends keyof FileRoutesByPath>(
193
path: TFilePath
194
): <TLoaderFn>(loaderFn: TLoaderFn) => TLoaderFn;
195
```
196
197
### File Route Class
198
199
File route class for programmatic file-based route creation (deprecated in favor of createFileRoute).
200
201
```typescript { .api }
202
/**
203
* File route class (deprecated - use createFileRoute instead)
204
* @deprecated Use createFileRoute('/path/to/file')(options) instead
205
*/
206
class FileRoute<
207
TFilePath extends keyof FileRoutesByPath,
208
TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],
209
TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],
210
TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],
211
TFullPath extends RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath']
212
> {
213
/** File path */
214
path?: TFilePath;
215
/** Silent mode flag */
216
silent?: boolean;
217
218
constructor(path?: TFilePath, opts?: { silent: boolean });
219
220
/**
221
* Create route from file route instance
222
* @param options - File route options
223
* @returns Route instance
224
*/
225
createRoute<TOptions extends FileBaseRouteOptions>(
226
options?: TOptions
227
): Route<TParentRoute, TPath, TFullPath, TFilePath, TId>;
228
}
229
```
230
231
**Usage Examples:**
232
233
```typescript
234
// In routes/index.tsx
235
export const Route = createFileRoute("/")({
236
component: Index,
237
});
238
239
function Index() {
240
return <div>Home</div>;
241
}
242
243
// In routes/posts/$postId.tsx
244
export const Route = createFileRoute("/posts/$postId")({
245
loader: ({ params }) => fetchPost(params.postId),
246
component: PostDetail,
247
});
248
249
// Lazy file route
250
export const Route = createLazyFileRoute("/posts/$postId")({
251
component: LazyPostDetail,
252
});
253
```
254
255
### Lazy Routes
256
257
Create routes that load components dynamically for code splitting with typed hook access.
258
259
```typescript { .api }
260
/**
261
* Create a lazy route for code splitting
262
* @param id - Route ID
263
* @returns Function to create lazy route
264
*/
265
function createLazyRoute<
266
TRouter extends AnyRouter = RegisteredRouter,
267
TId extends string = string,
268
TRoute extends AnyRoute = RouteById<TRouter['routeTree'], TId>
269
>(
270
id: ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>
271
): (opts: LazyRouteOptions) => LazyRoute<TRoute>;
272
273
interface LazyRouteOptions {
274
/** Lazy route component */
275
component?: LazyRouteComponent;
276
/** Lazy error component */
277
errorComponent?: ErrorRouteComponent;
278
/** Lazy pending component */
279
pendingComponent?: RouteComponent;
280
/** Lazy not found component */
281
notFoundComponent?: NotFoundRouteComponent;
282
}
283
```
284
285
### Lazy Route Class
286
287
Lazy route class with typed hooks for accessing route data.
288
289
```typescript { .api }
290
/**
291
* Lazy route class with typed hook access
292
*/
293
class LazyRoute<TRoute extends AnyRoute> {
294
/** Lazy route options including ID */
295
options: { id: string } & LazyRouteOptions;
296
297
constructor(opts: { id: string } & LazyRouteOptions);
298
299
/**
300
* Access match data for this lazy route
301
* @param opts - Match selection options
302
* @returns Route match data
303
*/
304
useMatch: UseMatchRoute<TRoute['id']>;
305
306
/**
307
* Access route context for this lazy route
308
* @param opts - Context selection options
309
* @returns Route context
310
*/
311
useRouteContext: UseRouteContextRoute<TRoute['id']>;
312
313
/**
314
* Access search params for this lazy route
315
* @param opts - Search selection options
316
* @returns Search parameters
317
*/
318
useSearch: UseSearchRoute<TRoute['id']>;
319
320
/**
321
* Access route params for this lazy route
322
* @param opts - Params selection options
323
* @returns Route parameters
324
*/
325
useParams: UseParamsRoute<TRoute['id']>;
326
327
/**
328
* Access loader dependencies for this lazy route
329
* @param opts - Loader deps selection options
330
* @returns Loader dependencies
331
*/
332
useLoaderDeps: UseLoaderDepsRoute<TRoute['id']>;
333
334
/**
335
* Access loader data for this lazy route
336
* @param opts - Loader data selection options
337
* @returns Loader data
338
*/
339
useLoaderData: UseLoaderDataRoute<TRoute['id']>;
340
341
/**
342
* Access navigation function for this lazy route
343
* @returns Typed navigation function
344
*/
345
useNavigate: () => UseNavigateResult<TRoute['fullPath']>;
346
}
347
```
348
349
### Route API
350
351
Access typed API for specific routes with helper methods.
352
353
```typescript { .api }
354
/**
355
* Get typed route API for a specific route
356
* @param id - Route ID
357
* @returns RouteApi instance
358
*/
359
function getRouteApi<TId extends string, TRouter extends AnyRouter = RegisteredRouter>(
360
id: TId
361
): RouteApi<TRouter, TId>;
362
363
class RouteApi<TRouter extends AnyRouter, TId extends RouteIds<TRouter>> {
364
/** Route ID */
365
id: TId;
366
367
/**
368
* Use loader data for this route
369
* @param opts - Options
370
* @returns Loader data
371
*/
372
useLoaderData<TSelected = ResolveLoaderData<TRouter, TId>>(
373
opts?: {
374
select?: (data: ResolveLoaderData<TRouter, TId>) => TSelected;
375
}
376
): TSelected;
377
378
/**
379
* Use route context
380
* @param opts - Options
381
* @returns Route context
382
*/
383
useRouteContext<TSelected = RouteContext<TRouter, TId>>(
384
opts?: {
385
select?: (context: RouteContext<TRouter, TId>) => TSelected;
386
}
387
): TSelected;
388
389
/**
390
* Use search params for this route
391
* @param opts - Options
392
* @returns Search params
393
*/
394
useSearch<TSelected = InferFullSearchSchema<TRouter, TId>>(
395
opts?: {
396
select?: (search: InferFullSearchSchema<TRouter, TId>) => TSelected;
397
}
398
): TSelected;
399
400
/**
401
* Use params for this route
402
* @param opts - Options
403
* @returns Route params
404
*/
405
useParams<TSelected = ResolveParams<TRouter, TId>>(
406
opts?: {
407
select?: (params: ResolveParams<TRouter, TId>) => TSelected;
408
}
409
): TSelected;
410
}
411
```
412
413
### Route Masking
414
415
Create route masks for URL masking and aliasing.
416
417
```typescript { .api }
418
/**
419
* Create a route mask for URL masking
420
* @param options - Masking options
421
* @returns Route mask configuration
422
*/
423
function createRouteMask<TRouteTree extends AnyRoute, TFrom extends string, TTo extends string>(
424
options: {
425
routeTree: TRouteTree;
426
from: TFrom;
427
to: TTo;
428
params?: Record<string, any>;
429
search?: Record<string, any>;
430
hash?: string;
431
unmaskOnReload?: boolean;
432
}
433
): RouteMask;
434
```
435
436
## Types
437
438
### Route Types
439
440
```typescript { .api }
441
interface Route<TParentRoute extends AnyRoute = AnyRoute> {
442
/** Route ID */
443
id: string;
444
/** Route path pattern */
445
path: string;
446
/** Full resolved path */
447
fullPath: string;
448
/** Parent route */
449
parentRoute?: TParentRoute;
450
/** Child routes */
451
children?: AnyRoute[];
452
/** Route options */
453
options: RouteOptions;
454
/** Add child routes */
455
addChildren<TChildren extends AnyRoute[]>(children: TChildren): RouteWithChildren<TChildren>;
456
}
457
458
interface RootRoute<TRouterContext = unknown> extends Route {
459
/** Root route marker */
460
isRoot: true;
461
/** Router context */
462
context?: TRouterContext;
463
}
464
```
465
466
### Route Match Types
467
468
```typescript { .api }
469
interface RouteMatch {
470
/** Match ID */
471
id: string;
472
/** Route ID this match represents */
473
routeId: string;
474
/** Pathname portion */
475
pathname: string;
476
/** Route parameters */
477
params: Record<string, any>;
478
/** Search parameters */
479
search: Record<string, any>;
480
/** Loader data */
481
loaderData?: any;
482
/** Route context */
483
context: RouteContext;
484
/** Match status */
485
status: "pending" | "success" | "error" | "idle";
486
/** Whether match is invalid */
487
invalid: boolean;
488
/** Error if any */
489
error?: unknown;
490
/** Updated timestamp */
491
updatedAt: number;
492
}
493
```
494
495
### Component Types
496
497
```typescript { .api }
498
type RouteComponent = React.ComponentType<{
499
useParams: () => any;
500
useSearch: () => any;
501
useLoaderData: () => any;
502
useRouteContext: () => any;
503
useNavigate: () => any;
504
}>;
505
506
type ErrorRouteComponent = React.ComponentType<{
507
error: Error;
508
info: { componentStack: string };
509
reset: () => void;
510
}>;
511
512
type NotFoundRouteComponent = React.ComponentType<{
513
data?: any;
514
}>;
515
```
516
517
### Loader Types
518
519
```typescript { .api }
520
type RouteLoaderFn<TRoute extends AnyRoute = AnyRoute> = (
521
context: LoaderFnContext<TRoute>
522
) => any | Promise<any>;
523
524
interface LoaderFnContext<TRoute extends AnyRoute = AnyRoute> {
525
/** Route parameters */
526
params: ResolveParams<TRoute>;
527
/** Search parameters */
528
search: InferFullSearchSchema<TRoute>;
529
/** Route context */
530
context: RouteContext<TRoute>;
531
/** Location object */
532
location: ParsedLocation;
533
/** Abort signal */
534
signal: AbortSignal;
535
}
536
```