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

index.md docs/

1
# TanStack React Router
2
3
TanStack React Router is a modern and scalable routing solution for React applications that provides end-to-end type safety, built-in data fetching, caching, and state management capabilities. It offers a comprehensive type-safe approach to routing with schema-driven search parameter validation, nested layouts with transitions and error boundaries, and advanced features like prefetching and invalidation.
4
5
## Package Information
6
7
- **Package Name**: @tanstack/react-router
8
- **Package Type**: npm
9
- **Language**: TypeScript
10
- **Installation**: `npm install @tanstack/react-router`
11
12
## Core Imports
13
14
```typescript
15
import {
16
Router, createRouter, RouterProvider,
17
Link, useNavigate, useParams, useSearch,
18
createRoute, createRootRoute, createFileRoute
19
} from "@tanstack/react-router";
20
```
21
22
For CommonJS:
23
24
```javascript
25
const {
26
Router, createRouter, RouterProvider,
27
Link, useNavigate, useParams, useSearch,
28
createRoute, createRootRoute, createFileRoute
29
} = require("@tanstack/react-router");
30
```
31
32
## Basic Usage
33
34
```typescript
35
import {
36
createRouter, RouterProvider, createRootRoute,
37
createRoute, Link, useNavigate, Outlet
38
} from "@tanstack/react-router";
39
40
// Create root route
41
const rootRoute = createRootRoute({
42
component: () => (
43
<div>
44
<nav>
45
<Link to="/">Home</Link>
46
<Link to="/about">About</Link>
47
</nav>
48
<Outlet />
49
</div>
50
),
51
});
52
53
// Create route
54
const indexRoute = createRoute({
55
getParentRoute: () => rootRoute,
56
path: "/",
57
component: () => <div>Welcome Home!</div>,
58
});
59
60
const aboutRoute = createRoute({
61
getParentRoute: () => rootRoute,
62
path: "/about",
63
component: () => <div>About Page</div>,
64
});
65
66
// Create router
67
const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]);
68
const router = createRouter({ routeTree });
69
70
// Use in app
71
function App() {
72
return <RouterProvider router={router} />;
73
}
74
```
75
76
## Architecture
77
78
TanStack React Router is built around several key architectural components:
79
80
- **Router Core**: Central router instance managing navigation state, route matching, and lifecycle
81
- **Route Definition System**: Declarative route creation with type-safe parameter and search handling
82
- **Component System**: React components for navigation (Link), rendering (Match, Outlet), and error handling
83
- **Hook System**: React hooks for accessing router state, navigation, and route data
84
- **Data Loading**: Integrated loader system with caching, invalidation, and error boundaries
85
- **SSR Support**: Full server-side rendering capabilities with hydration
86
- **File-based Routing**: Optional file-based route organization with automatic type generation
87
88
## Capabilities
89
90
### Router Creation & Configuration
91
92
Core router setup and configuration for creating type-safe routing instances with comprehensive options for data loading, caching, and error handling.
93
94
```typescript { .api }
95
function createRouter<TRouteTree extends AnyRoute>(
96
options: RouterConstructorOptions<TRouteTree>
97
): Router<TRouteTree>;
98
99
interface RouterConstructorOptions<TRouteTree extends AnyRoute> {
100
routeTree: TRouteTree;
101
history?: RouterHistory;
102
basepath?: string;
103
context?: TRouterContext;
104
defaultPreload?: false | "intent" | "render" | "viewport";
105
defaultComponent?: RouteComponent;
106
defaultErrorComponent?: ErrorRouteComponent;
107
defaultNotFoundComponent?: NotFoundRouteComponent;
108
}
109
```
110
111
[Router Creation & Configuration](./router-creation.md)
112
113
### Route Definition & Management
114
115
System for defining routes with type-safe parameters, search handling, data loading, and nested layouts.
116
117
```typescript { .api }
118
function createRoute<TParentRoute extends AnyRoute = AnyRoute>(
119
options: RouteOptions<TParentRoute>
120
): Route<TParentRoute>;
121
122
function createRootRoute<TRouterContext = unknown>(
123
options?: RootRouteOptions<TRouterContext>
124
): RootRoute<TRouterContext>;
125
126
function createFileRoute<TFilePath extends string>(
127
path?: TFilePath
128
): FileRoute;
129
```
130
131
[Route Definition & Management](./route-definition.md)
132
133
### React Components
134
135
Essential React components for router setup, navigation, route rendering, and error handling.
136
137
```typescript { .api }
138
function RouterProvider<TRouter extends AnyRouter, TDehydrated = unknown>(
139
props: RouterProps<TRouter, TDehydrated>
140
): JSX.Element;
141
142
function Link<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string>(
143
props: LinkProps<TRouter, TFrom>
144
): JSX.Element;
145
146
function Match(props: { matchId: string }): JSX.Element;
147
148
function Outlet(): JSX.Element;
149
```
150
151
[React Components](./react-components.md)
152
153
### React Hooks
154
155
React hooks for accessing router state, navigation functions, route data, and parameters.
156
157
```typescript { .api }
158
function useRouter<TRouter extends AnyRouter = RegisteredRouter>(): TRouter;
159
160
function useNavigate<TRouter extends AnyRouter = RegisteredRouter>():
161
UseNavigateResult<TRouter>;
162
163
function useParams<TRouter extends AnyRouter = RegisteredRouter>(
164
opts?: UseParamsOptions
165
): ResolveParams<TRouter>;
166
167
function useSearch<TRouter extends AnyRouter = RegisteredRouter>(
168
opts?: UseSearchOptions
169
): InferFullSearchSchema<TRouter>;
170
```
171
172
[React Hooks](./react-hooks.md)
173
174
### Navigation & Links
175
176
Navigation utilities, link components, and programmatic navigation with type-safe parameter handling.
177
178
```typescript { .api }
179
function redirect<TRouter extends AnyRouter = AnyRouter>(
180
options: RedirectOptions<TRouter>
181
): Redirect;
182
183
function createLink<TComp extends React.ComponentType<any>>(
184
Comp: TComp
185
): LinkComponent<TComp>;
186
187
function linkOptions<TRouter extends AnyRouter, TFrom extends string>(
188
options: LinkOptions<TRouter, TFrom>
189
): LinkOptions<TRouter, TFrom>;
190
```
191
192
[Navigation & Links](./navigation-links.md)
193
194
### Data Loading & Caching
195
196
Built-in data loading system with loaders, caching, invalidation, and promise handling.
197
198
```typescript { .api }
199
function defer<T>(promise: Promise<T>): DeferredPromise<T>;
200
201
function useLoaderData<TRouter extends AnyRouter = RegisteredRouter>(
202
opts?: UseLoaderDataOptions
203
): ResolveLoaderData<TRouter>;
204
205
function useAwaited<T>(options: AwaitOptions<T>): [T, DeferredPromise<T>];
206
```
207
208
[Data Loading & Caching](./data-loading.md)
209
210
### Error Handling
211
212
Comprehensive error handling with boundaries, not found handling, and custom error components.
213
214
```typescript { .api }
215
function CatchBoundary(props: CatchBoundaryProps): JSX.Element;
216
217
function notFound<TRouterContext = unknown>(
218
options?: NotFoundError
219
): NotFoundError;
220
221
function isNotFound(obj: any): obj is NotFoundError;
222
223
function isRedirect(obj: any): obj is Redirect;
224
```
225
226
[Error Handling](./error-handling.md)
227
228
### Server-Side Rendering
229
230
Complete SSR support with server and client components, rendering utilities, and hydration.
231
232
```typescript { .api }
233
function renderRouterToString<TRouter extends AnyRouter>(
234
options: RenderRouterToStringOptions<TRouter>
235
): Promise<string>;
236
237
function renderRouterToStream<TRouter extends AnyRouter>(
238
options: RenderRouterToStreamOptions<TRouter>
239
): Promise<ReadableStream>;
240
```
241
242
[Server-Side Rendering](./ssr.md)
243
244
### Path & Search Utilities
245
246
Low-level utilities for path manipulation, search parameter handling, and URL processing.
247
248
```typescript { .api }
249
function joinPaths(paths: Array<string | undefined>): string;
250
251
function parseSearchWith<T>(parser: (searchStr: string) => T): (searchStr: string) => T;
252
253
function retainSearchParams<T>(search: T, retain: Array<string | number>): Partial<T>;
254
255
function interpolatePath(path: string, params: Record<string, any>): string;
256
```
257
258
[Path & Search Utilities](./path-search-utils.md)
259
260
## Types
261
262
### Core Router Types
263
264
```typescript { .api }
265
interface Router<TRouteTree extends AnyRoute = AnyRoute> {
266
history: RouterHistory;
267
state: RouterState;
268
navigate: (options: NavigateOptions) => Promise<void>;
269
buildLocation: (options: BuildLocationOptions) => ParsedLocation;
270
invalidate: () => Promise<void>;
271
}
272
273
interface RouterState {
274
location: ParsedLocation;
275
matches: RouteMatch[];
276
pendingMatches?: RouteMatch[];
277
isLoading: boolean;
278
isTransitioning: boolean;
279
}
280
281
interface ParsedLocation {
282
pathname: string;
283
search: Record<string, any>;
284
searchStr: string;
285
hash: string;
286
href: string;
287
state: HistoryState;
288
}
289
```
290
291
### Route Types
292
293
```typescript { .api }
294
interface Route<TParentRoute extends AnyRoute = AnyRoute> {
295
id: string;
296
path: string;
297
fullPath: string;
298
parentRoute?: TParentRoute;
299
children?: AnyRoute[];
300
options: RouteOptions;
301
}
302
303
interface RouteMatch {
304
id: string;
305
routeId: string;
306
pathname: string;
307
params: Record<string, any>;
308
search: Record<string, any>;
309
loaderData?: any;
310
context: RouteContext;
311
status: "pending" | "success" | "error" | "idle";
312
}
313
```
314
315
### Navigation Types
316
317
```typescript { .api }
318
interface NavigateOptions<TRouter extends AnyRouter = AnyRouter> {
319
to?: string;
320
from?: string;
321
params?: Record<string, any>;
322
search?: Record<string, any> | ((prev: any) => Record<string, any>);
323
hash?: string | ((prev: string) => string);
324
state?: any;
325
replace?: boolean;
326
resetScroll?: boolean;
327
startTransition?: boolean;
328
}
329
330
interface LinkOptions<TRouter extends AnyRouter = AnyRouter> extends NavigateOptions<TRouter> {
331
activeProps?: React.AnchorHTMLAttributes<HTMLAnchorElement>;
332
inactiveProps?: React.AnchorHTMLAttributes<HTMLAnchorElement>;
333
preload?: false | "intent" | "render" | "viewport";
334
preloadDelay?: number;
335
}
336
```