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

router-creation.md docs/

1
# Router Creation & Configuration
2
3
Core router setup and configuration for creating type-safe routing instances with comprehensive options for data loading, caching, error handling, and SSR support.
4
5
## Capabilities
6
7
### Router Creation
8
9
Creates a new router instance with the specified route tree and configuration options.
10
11
```typescript { .api }
12
/**
13
* Create a router instance with route tree and configuration
14
* @param options - Router configuration options including route tree, history, and defaults
15
* @returns Router instance for use with RouterProvider
16
*/
17
function createRouter<TRouteTree extends AnyRoute>(
18
options: RouterConstructorOptions<TRouteTree>
19
): Router<TRouteTree>;
20
21
interface RouterConstructorOptions<TRouteTree extends AnyRoute> {
22
/** The route tree defining all application routes */
23
routeTree: TRouteTree;
24
/** History instance for navigation (defaults to createBrowserHistory()) */
25
history?: RouterHistory;
26
/** Base path for the router */
27
basepath?: string;
28
/** Router context shared across all routes */
29
context?: TRouterContext;
30
/** Default preload strategy for routes */
31
defaultPreload?: false | "intent" | "render" | "viewport";
32
/** Default preload delay in milliseconds */
33
defaultPreloadDelay?: number;
34
/** Default component used when route has no component */
35
defaultComponent?: RouteComponent;
36
/** Default error component for route errors */
37
defaultErrorComponent?: ErrorRouteComponent;
38
/** Default pending component shown during loading */
39
defaultPendingComponent?: RouteComponent;
40
/** Default not found component for 404 errors */
41
defaultNotFoundComponent?: NotFoundRouteComponent;
42
/** Minimum time to show pending component */
43
defaultPendingMinMs?: number;
44
/** Default time before showing pending component */
45
defaultPendingMs?: number;
46
/** Default stale time for route data */
47
defaultStaleTime?: number;
48
/** Default garbage collection time */
49
defaultGcTime?: number;
50
/** Whether routes are case sensitive */
51
caseSensitive?: boolean;
52
/** Trailing slash handling */
53
trailingSlash?: "always" | "never" | "preserve";
54
/** Enable structural sharing by default */
55
defaultStructuralSharing?: boolean;
56
/** Router wrapper component */
57
Wrap?: (props: { children: React.ReactNode }) => JSX.Element;
58
/** Inner router wrapper component */
59
InnerWrap?: (props: { children: React.ReactNode }) => JSX.Element;
60
/** Default error handler */
61
defaultOnCatch?: (error: Error, errorInfo: ErrorInfo) => void;
62
}
63
```
64
65
**Usage Examples:**
66
67
```typescript
68
import { createRouter, createBrowserHistory } from "@tanstack/react-router";
69
70
// Basic router creation
71
const router = createRouter({
72
routeTree,
73
});
74
75
// Router with custom configuration
76
const router = createRouter({
77
routeTree,
78
basepath: "/app",
79
defaultPreload: "intent",
80
defaultStaleTime: 5000,
81
caseSensitive: true,
82
trailingSlash: "never",
83
defaultComponent: () => <div>Loading...</div>,
84
defaultErrorComponent: ({ error }) => <div>Error: {error.message}</div>,
85
});
86
87
// Router with custom history
88
const customHistory = createBrowserHistory();
89
const router = createRouter({
90
routeTree,
91
history: customHistory,
92
context: {
93
user: { id: "123", name: "John" },
94
theme: "dark",
95
},
96
});
97
```
98
99
### Router Configuration
100
101
Creates a router configuration object for advanced scenarios.
102
103
```typescript { .api }
104
/**
105
* Create a router configuration object
106
* @param config - Router configuration
107
* @returns Router configuration object
108
*/
109
function createRouterConfig<TRouteTree extends AnyRoute>(
110
config: RouterConstructorOptions<TRouteTree>
111
): RouterConfig<TRouteTree>;
112
```
113
114
### Router Class
115
116
The main router class that manages navigation state, route matching, and lifecycle.
117
118
```typescript { .api }
119
class Router<TRouteTree extends AnyRoute = AnyRoute> {
120
/** Router history instance */
121
history: RouterHistory;
122
/** Current router state */
123
state: RouterState<TRouteTree>;
124
/** Route tree */
125
routeTree: TRouteTree;
126
/** Router options */
127
options: RouterOptions;
128
129
/**
130
* Navigate to a new location
131
* @param options - Navigation options
132
* @returns Promise that resolves when navigation completes
133
*/
134
navigate<TFrom extends RoutePaths<TRouteTree> = "/">(
135
options: NavigateOptions<TRouteTree, TFrom>
136
): Promise<void>;
137
138
/**
139
* Build a location object from navigation options
140
* @param options - Navigation options
141
* @returns Parsed location object
142
*/
143
buildLocation<TFrom extends RoutePaths<TRouteTree> = "/">(
144
options: BuildLocationOptions<TRouteTree, TFrom>
145
): ParsedLocation;
146
147
/**
148
* Invalidate all route matches
149
* @returns Promise that resolves when invalidation completes
150
*/
151
invalidate(): Promise<void>;
152
153
/**
154
* Load a route by location
155
* @param location - Location to load
156
* @returns Promise that resolves when loading completes
157
*/
158
load(location?: ParsedLocation): Promise<void>;
159
160
/**
161
* Preload a route
162
* @param options - Navigation options for route to preload
163
* @returns Promise that resolves when preloading completes
164
*/
165
preloadRoute<TFrom extends RoutePaths<TRouteTree> = "/">(
166
options: NavigateOptions<TRouteTree, TFrom>
167
): Promise<void>;
168
169
/**
170
* Subscribe to router state changes
171
* @param fn - Listener function
172
* @returns Unsubscribe function
173
*/
174
subscribe(fn: (state: RouterState<TRouteTree>) => void): () => void;
175
176
/**
177
* Match routes for a location
178
* @param location - Location to match
179
* @returns Array of route matches
180
*/
181
matchRoutes(location: ParsedLocation): RouteMatch[];
182
}
183
```
184
185
## Types
186
187
### Router State
188
189
```typescript { .api }
190
interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {
191
/** Current location */
192
location: ParsedLocation;
193
/** Currently matched routes */
194
matches: RouteMatch[];
195
/** Pending matches during navigation */
196
pendingMatches?: RouteMatch[];
197
/** Whether router is in loading state */
198
isLoading: boolean;
199
/** Whether router is transitioning between routes */
200
isTransitioning: boolean;
201
/** Last updated timestamp */
202
lastUpdated: number;
203
/** Navigation status */
204
status: "idle" | "pending" | "success" | "error";
205
}
206
```
207
208
### Router Events
209
210
```typescript { .api }
211
interface RouterEvents {
212
onBeforeLoad: (event: {
213
router: Router;
214
fromLocation: ParsedLocation;
215
toLocation: ParsedLocation;
216
}) => void;
217
onLoad: (event: {
218
router: Router;
219
fromLocation: ParsedLocation;
220
toLocation: ParsedLocation;
221
}) => void;
222
onBeforeNavigate: (event: {
223
router: Router;
224
fromLocation: ParsedLocation;
225
toLocation: ParsedLocation;
226
}) => void;
227
onNavigate: (event: {
228
router: Router;
229
fromLocation: ParsedLocation;
230
toLocation: ParsedLocation;
231
}) => void;
232
}
233
```
234
235
### History Types
236
237
```typescript { .api }
238
interface RouterHistory {
239
/** Current location */
240
location: HistoryLocation;
241
/** Go back in history */
242
back(): void;
243
/** Go forward in history */
244
forward(): void;
245
/** Go to specific history entry */
246
go(n: number): void;
247
/** Push new location */
248
push(path: string, state?: any): void;
249
/** Replace current location */
250
replace(path: string, state?: any): void;
251
/** Create href for path */
252
createHref(path: string): string;
253
/** Subscribe to location changes */
254
subscribe(fn: (location: HistoryLocation) => void): () => void;
255
}
256
257
interface HistoryLocation {
258
pathname: string;
259
search: string;
260
hash: string;
261
state?: any;
262
key?: string;
263
}
264
```