0
# Navigation Hooks
1
2
Hooks for accessing routing state and performing navigation operations, including location access, parameter extraction, and programmatic navigation.
3
4
## Capabilities
5
6
### useNavigate
7
8
Returns a function for programmatic navigation.
9
10
```typescript { .api }
11
/**
12
* Hook that returns a function for programmatic navigation
13
* @returns Navigation function for changing routes
14
*/
15
function useNavigate(): NavigateFunction;
16
17
interface NavigateFunction {
18
/** Navigate to a specific location */
19
(to: To, options?: NavigateOptions): void;
20
/** Navigate relative to history (back/forward) */
21
(delta: number): void;
22
}
23
24
interface NavigateOptions {
25
/** Replace current entry instead of pushing new entry */
26
replace?: boolean;
27
/** State object to pass with navigation */
28
state?: any;
29
/** Enable relative path resolution */
30
relative?: RelativeRoutingType;
31
/** Prevent scroll reset on navigation */
32
preventScrollReset?: boolean;
33
/** Flash the element after navigation */
34
unstable_flushSync?: boolean;
35
/** View transition name for page transitions */
36
unstable_viewTransition?: boolean;
37
}
38
39
type To = string | Partial<Path>;
40
type RelativeRoutingType = "route" | "path";
41
```
42
43
**Usage Examples:**
44
45
```tsx
46
import { useNavigate } from "react-router-dom";
47
48
function MyComponent() {
49
const navigate = useNavigate();
50
51
const handleSubmit = async (formData) => {
52
await saveData(formData);
53
// Navigate to success page
54
navigate("/success");
55
};
56
57
const goBack = () => {
58
// Go back one entry in history
59
navigate(-1);
60
};
61
62
const redirectWithState = () => {
63
navigate("/profile", {
64
state: { from: "settings" },
65
replace: true
66
});
67
};
68
69
return (
70
<div>
71
<button onClick={handleSubmit}>Save</button>
72
<button onClick={goBack}>Back</button>
73
<button onClick={redirectWithState}>Go to Profile</button>
74
</div>
75
);
76
}
77
```
78
79
### useLocation
80
81
Returns the current location object representing the current URL.
82
83
```typescript { .api }
84
/**
85
* Hook that returns the current location object
86
* @returns Current location with pathname, search, hash, and state
87
*/
88
function useLocation(): Location;
89
90
interface Location {
91
/** URL pathname */
92
pathname: string;
93
/** URL search parameters as string */
94
search: string;
95
/** URL hash fragment */
96
hash: string;
97
/** State object passed with navigation */
98
state: unknown;
99
/** Unique key for this location */
100
key: string;
101
}
102
```
103
104
**Usage Examples:**
105
106
```tsx
107
import { useLocation } from "react-router-dom";
108
109
function LocationDisplay() {
110
const location = useLocation();
111
112
return (
113
<div>
114
<p>Current Path: {location.pathname}</p>
115
<p>Search: {location.search}</p>
116
<p>Hash: {location.hash}</p>
117
<p>State: {JSON.stringify(location.state)}</p>
118
</div>
119
);
120
}
121
122
// Conditional rendering based on location
123
function Navigation() {
124
const location = useLocation();
125
const isHomePage = location.pathname === "/";
126
127
return (
128
<nav className={isHomePage ? "home-nav" : "page-nav"}>
129
{/* Navigation content */}
130
</nav>
131
);
132
}
133
```
134
135
### useParams
136
137
Returns parameters from the current route as key-value pairs.
138
139
```typescript { .api }
140
/**
141
* Hook that returns route parameters from the current URL
142
* @returns Object containing route parameters
143
*/
144
function useParams<K extends string = string>(): Readonly<Params<K>>;
145
146
interface Params<K extends string = string> {
147
readonly [key in K]: string | undefined;
148
}
149
```
150
151
**Usage Examples:**
152
153
```tsx
154
import { useParams } from "react-router-dom";
155
156
// Route: /users/:userId/posts/:postId
157
function UserPost() {
158
const { userId, postId } = useParams();
159
160
// TypeScript users can specify parameter types
161
const params = useParams<"userId" | "postId">();
162
163
return (
164
<div>
165
<h1>User {userId}</h1>
166
<h2>Post {postId}</h2>
167
</div>
168
);
169
}
170
171
// Optional parameters
172
// Route: /products/:category/:productId?
173
function Product() {
174
const { category, productId } = useParams();
175
176
if (!productId) {
177
return <CategoryView category={category} />;
178
}
179
180
return <ProductView category={category} productId={productId} />;
181
}
182
```
183
184
### useSearchParams
185
186
Provides access to URL search parameters with setter function.
187
188
```typescript { .api }
189
/**
190
* Hook for reading and updating URL search parameters
191
* @param defaultInit - Default search parameters
192
* @returns Tuple of current search params and setter function
193
*/
194
function useSearchParams(
195
defaultInit?: URLSearchParamsInit
196
): [URLSearchParams, SetURLSearchParams];
197
198
type SetURLSearchParams = (
199
nextInit: URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit),
200
navigateOptions?: NavigateOptions
201
) => void;
202
203
type URLSearchParamsInit =
204
| string
205
| string[][]
206
| Record<string, string | string[]>
207
| URLSearchParams;
208
```
209
210
**Usage Examples:**
211
212
```tsx
213
import { useSearchParams } from "react-router-dom";
214
215
function SearchPage() {
216
const [searchParams, setSearchParams] = useSearchParams();
217
218
const query = searchParams.get("q") || "";
219
const category = searchParams.get("category") || "all";
220
221
const updateQuery = (newQuery: string) => {
222
setSearchParams(prev => {
223
prev.set("q", newQuery);
224
return prev;
225
});
226
};
227
228
const updateCategory = (newCategory: string) => {
229
setSearchParams({
230
q: query,
231
category: newCategory
232
});
233
};
234
235
return (
236
<div>
237
<input
238
value={query}
239
onChange={e => updateQuery(e.target.value)}
240
placeholder="Search..."
241
/>
242
<select
243
value={category}
244
onChange={e => updateCategory(e.target.value)}
245
>
246
<option value="all">All Categories</option>
247
<option value="books">Books</option>
248
<option value="electronics">Electronics</option>
249
</select>
250
</div>
251
);
252
}
253
```
254
255
### useHref
256
257
Generates href string for a given destination.
258
259
```typescript { .api }
260
/**
261
* Hook that returns an href string for a given destination
262
* @param to - Navigation destination
263
* @param options - Href generation options
264
* @returns Href string for the destination
265
*/
266
function useHref(to: To, options?: { relative?: RelativeRoutingType }): string;
267
```
268
269
**Usage Examples:**
270
271
```tsx
272
import { useHref } from "react-router-dom";
273
274
function CustomLink({ to, children, ...props }) {
275
const href = useHref(to);
276
277
return (
278
<a href={href} {...props}>
279
{children}
280
</a>
281
);
282
}
283
284
// Generate href for external use
285
function ShareButton() {
286
const currentHref = useHref(".", { relative: "path" });
287
const fullUrl = `${window.location.origin}${currentHref}`;
288
289
const share = () => {
290
navigator.share({ url: fullUrl });
291
};
292
293
return <button onClick={share}>Share</button>;
294
}
295
```
296
297
### useResolvedPath
298
299
Resolves a path against the current location.
300
301
```typescript { .api }
302
/**
303
* Hook that resolves a relative path against the current location
304
* @param to - Path to resolve
305
* @param options - Path resolution options
306
* @returns Resolved path object
307
*/
308
function useResolvedPath(
309
to: To,
310
options?: { relative?: RelativeRoutingType }
311
): Path;
312
313
interface Path {
314
pathname: string;
315
search: string;
316
hash: string;
317
}
318
```
319
320
**Usage Example:**
321
322
```tsx
323
import { useResolvedPath, useMatch } from "react-router-dom";
324
325
function CustomNavLink({ to, children, ...props }) {
326
const resolved = useResolvedPath(to);
327
const match = useMatch({ path: resolved.pathname, end: true });
328
329
return (
330
<a
331
href={resolved.pathname + resolved.search + resolved.hash}
332
className={match ? "active" : ""}
333
{...props}
334
>
335
{children}
336
</a>
337
);
338
}
339
```
340
341
### useMatch
342
343
Returns match information for a given path pattern.
344
345
```typescript { .api }
346
/**
347
* Hook that returns match information for a path pattern
348
* @param pattern - Path pattern to match against
349
* @returns Match object or null if no match
350
*/
351
function useMatch<T extends Record<string, any>>(
352
pattern: PathPattern<T> | string
353
): PathMatch<T> | null;
354
355
interface PathPattern<T extends Record<string, any> = Record<string, any>> {
356
path: string;
357
caseSensitive?: boolean;
358
end?: boolean;
359
}
360
361
interface PathMatch<T extends Record<string, any> = Record<string, any>> {
362
params: T;
363
pathname: string;
364
pathnameBase: string;
365
pattern: PathPattern<T>;
366
}
367
```
368
369
**Usage Example:**
370
371
```tsx
372
import { useMatch } from "react-router-dom";
373
374
function UserProfileTab() {
375
const match = useMatch("/users/:userId/profile");
376
377
if (match) {
378
return (
379
<div>
380
Currently viewing profile for user {match.params.userId}
381
</div>
382
);
383
}
384
385
return null;
386
}
387
```
388
389
### useMatches
390
391
Returns an array of current route matches.
392
393
```typescript { .api }
394
/**
395
* Hook that returns the current route match hierarchy
396
* @returns Array of route matches from root to current
397
*/
398
function useMatches(): UIMatch[];
399
400
interface UIMatch<Data = unknown, Handle = unknown> {
401
/** Route ID */
402
id: string;
403
/** Matched pathname */
404
pathname: string;
405
/** Route parameters */
406
params: Params;
407
/** Route loader data */
408
data: Data;
409
/** Route handle data */
410
handle: Handle;
411
}
412
```
413
414
**Usage Example:**
415
416
```tsx
417
import { useMatches } from "react-router-dom";
418
419
function Breadcrumbs() {
420
const matches = useMatches();
421
422
const crumbs = matches
423
.filter(match => match.handle?.crumb)
424
.map(match => match.handle.crumb(match));
425
426
return (
427
<nav>
428
{crumbs.map((crumb, index) => (
429
<span key={index}>
430
{crumb}
431
{index < crumbs.length - 1 && " > "}
432
</span>
433
))}
434
</nav>
435
);
436
}
437
```
438
439
### useRouteError
440
441
Hook for accessing route errors in error boundary components.
442
443
```typescript { .api }
444
/**
445
* Hook that returns the error thrown during route loading or rendering
446
* @returns Error object thrown in current route context
447
*/
448
function useRouteError(): unknown;
449
```
450
451
**Usage Examples:**
452
453
```tsx
454
import { useRouteError, isRouteErrorResponse } from "react-router-dom";
455
456
function ErrorBoundary() {
457
const error = useRouteError();
458
459
if (isRouteErrorResponse(error)) {
460
return (
461
<div>
462
<h1>Error {error.status}</h1>
463
<p>{error.statusText}</p>
464
{error.data && <p>{error.data}</p>}
465
</div>
466
);
467
}
468
469
return (
470
<div>
471
<h1>Something went wrong</h1>
472
<p>{error instanceof Error ? error.message : "Unknown error"}</p>
473
</div>
474
);
475
}
476
477
// Usage in route configuration
478
const routes = [
479
{
480
path: "/users/:id",
481
element: <User />,
482
errorElement: <ErrorBoundary />,
483
loader: async ({ params }) => {
484
const response = await fetch(`/api/users/${params.id}`);
485
if (!response.ok) {
486
throw new Response("User not found", { status: 404 });
487
}
488
return response.json();
489
},
490
},
491
];
492
```
493
494
### useOutlet
495
496
Hook that returns the current route outlet element.
497
498
```typescript { .api }
499
/**
500
* Hook that returns the outlet element for current route
501
* @param context - Optional context to pass to child routes
502
* @returns JSX element for route outlet or null
503
*/
504
function useOutlet(context?: unknown): React.ReactElement | null;
505
```
506
507
**Usage Examples:**
508
509
```tsx
510
import { useOutlet } from "react-router-dom";
511
512
function Layout() {
513
const outlet = useOutlet();
514
515
return (
516
<div className="layout">
517
<header>My App</header>
518
<nav>
519
<Link to="/">Home</Link>
520
<Link to="/about">About</Link>
521
</nav>
522
<main>
523
{outlet || <div>No route matched</div>}
524
</main>
525
</div>
526
);
527
}
528
529
// With context
530
function LayoutWithContext() {
531
const outlet = useOutlet({ theme: "dark", user: currentUser });
532
533
return (
534
<div className="layout">
535
{outlet}
536
</div>
537
);
538
}
539
540
// Child route accessing context
541
function ChildRoute() {
542
const context = useOutletContext<{ theme: string; user: User }>();
543
544
return (
545
<div className={`theme-${context.theme}`}>
546
Welcome, {context.user.name}!
547
</div>
548
);
549
}
550
```
551
552
### Navigation State Hooks
553
554
Additional hooks for navigation state management.
555
556
```typescript { .api }
557
/**
558
* Hook that returns navigation type for current location
559
* @returns Navigation type (POP, PUSH, or REPLACE)
560
*/
561
function useNavigationType(): NavigationType;
562
563
/**
564
* Hook that checks if component is inside a router context
565
* @returns True if inside router, false otherwise
566
*/
567
function useInRouterContext(): boolean;
568
569
type NavigationType = "POP" | "PUSH" | "REPLACE";
570
```
571
572
**Usage Examples:**
573
574
```tsx
575
import { useNavigationType, useInRouterContext } from "react-router-dom";
576
577
function NavigationInfo() {
578
const navigationType = useNavigationType();
579
const inRouter = useInRouterContext();
580
581
if (!inRouter) {
582
return <div>Not in router context</div>;
583
}
584
585
return (
586
<div>
587
Last navigation was: {navigationType}
588
{navigationType === "POP" && " (back/forward button)"}
589
{navigationType === "PUSH" && " (new entry)"}
590
{navigationType === "REPLACE" && " (replaced entry)"}
591
</div>
592
);
593
}
594
```