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