0
# Navigation Hooks
1
2
Core hooks for accessing navigation functionality from anywhere in the component tree, providing navigation methods, route information, screen lifecycle management, and navigation state access.
3
4
## Capabilities
5
6
### useNavigation
7
8
Hook to access the navigation prop of the parent screen from any component in the tree.
9
10
```typescript { .api }
11
/**
12
* Hook to access navigation functionality from any component
13
* @returns Navigation object with methods for navigation control
14
*/
15
function useNavigation<T = NavigationProp<ParamListBase>>(): T;
16
17
interface NavigationProp<ParamList extends ParamListBase = ParamListBase> {
18
/** Navigate to a screen by name with optional parameters */
19
navigate<RouteName extends keyof ParamList>(
20
name: RouteName,
21
params?: ParamList[RouteName]
22
): void;
23
/** Navigate to a screen with detailed options */
24
navigate<RouteName extends keyof ParamList>(options: {
25
name: RouteName;
26
params?: ParamList[RouteName];
27
merge?: boolean;
28
pop?: boolean;
29
}): void;
30
/** Go back to the previous screen */
31
goBack(): void;
32
/** Dispatch a navigation action */
33
dispatch(action: NavigationAction | ((state: NavigationState) => NavigationAction)): void;
34
/** Update screen options */
35
setOptions(options: Partial<ScreenOptions>): void;
36
/** Check if the current screen is focused */
37
isFocused(): boolean;
38
/** Check if navigation can go back */
39
canGoBack(): boolean;
40
/** Get the current navigation state */
41
getState(): NavigationState;
42
/** Get parent navigator by optional ID */
43
getParent<T = NavigationProp<ParamListBase> | undefined>(id?: string): T;
44
/** Update route parameters */
45
setParams(params: Partial<ParamList[keyof ParamList]>): void;
46
/** Reset navigation state */
47
reset(state: PartialState<NavigationState> | NavigationState): void;
48
/** Get navigator ID */
49
getId(): string | undefined;
50
/** Preload a screen */
51
preload<RouteName extends keyof ParamList>(
52
name: RouteName,
53
params?: ParamList[RouteName]
54
): void;
55
}
56
```
57
58
**Usage Examples:**
59
60
```typescript
61
import { useNavigation } from "@react-navigation/core";
62
63
function MyComponent() {
64
const navigation = useNavigation();
65
66
const handleNavigate = () => {
67
// Navigate to a screen
68
navigation.navigate('Profile', { userId: '123' });
69
70
// Navigate with options
71
navigation.navigate({
72
name: 'Profile',
73
params: { userId: '123' },
74
merge: true
75
});
76
};
77
78
const handleGoBack = () => {
79
if (navigation.canGoBack()) {
80
navigation.goBack();
81
}
82
};
83
84
return (
85
<View>
86
<Button title="Go to Profile" onPress={handleNavigate} />
87
<Button title="Go Back" onPress={handleGoBack} />
88
</View>
89
);
90
}
91
```
92
93
### useRoute
94
95
Hook to access the route prop of the parent screen from any component in the tree.
96
97
```typescript { .api }
98
/**
99
* Hook to access current route information
100
* @returns Route object containing name, key, params, and path
101
*/
102
function useRoute<T = RouteProp<ParamListBase>>(): T;
103
104
interface RouteProp<
105
ParamList extends ParamListBase = ParamListBase,
106
RouteName extends keyof ParamList = keyof ParamList
107
> {
108
/** Unique route identifier */
109
key: string;
110
/** Route name */
111
name: RouteName;
112
/** Route parameters */
113
params: ParamList[RouteName];
114
/** Optional path for deep linking */
115
path?: string;
116
/** Optional nested navigation state */
117
state?: NavigationState | PartialState<NavigationState>;
118
}
119
```
120
121
**Usage Examples:**
122
123
```typescript
124
import { useRoute } from "@react-navigation/core";
125
126
function ProfileScreen() {
127
const route = useRoute();
128
129
return (
130
<View>
131
<Text>Screen: {route.name}</Text>
132
<Text>User ID: {route.params?.userId}</Text>
133
<Text>Route Key: {route.key}</Text>
134
</View>
135
);
136
}
137
138
// Type-safe usage with proper param typing
139
type RootParamList = {
140
Profile: { userId: string; tab?: string };
141
Settings: undefined;
142
};
143
144
function TypedProfileScreen() {
145
const route = useRoute<RouteProp<RootParamList, 'Profile'>>();
146
147
// route.params is now properly typed
148
const { userId, tab } = route.params;
149
150
return (
151
<View>
152
<Text>User: {userId}</Text>
153
{tab && <Text>Tab: {tab}</Text>}
154
</View>
155
);
156
}
157
```
158
159
### useIsFocused
160
161
Hook to get the current focus state of the screen. Returns `true` if the screen is focused, `false` otherwise.
162
163
```typescript { .api }
164
/**
165
* Hook to check if the current screen is focused
166
* @returns Boolean indicating focus state
167
*/
168
function useIsFocused(): boolean;
169
```
170
171
**Usage Examples:**
172
173
```typescript
174
import { useIsFocused } from "@react-navigation/core";
175
176
function MyScreen() {
177
const isFocused = useIsFocused();
178
179
// Conditionally render based on focus
180
if (!isFocused) {
181
return <View><Text>Screen is not focused</Text></View>;
182
}
183
184
return (
185
<View>
186
<Text>Screen is focused!</Text>
187
<StatusBar barStyle="dark-content" />
188
</View>
189
);
190
}
191
192
// Using with effects
193
function TimerScreen() {
194
const isFocused = useIsFocused();
195
const [count, setCount] = useState(0);
196
197
useEffect(() => {
198
let interval;
199
if (isFocused) {
200
interval = setInterval(() => {
201
setCount(c => c + 1);
202
}, 1000);
203
}
204
return () => clearInterval(interval);
205
}, [isFocused]);
206
207
return <Text>Count: {count}</Text>;
208
}
209
```
210
211
### useFocusEffect
212
213
Hook to run side effects when screen comes into focus, similar to `useEffect` but focus-aware.
214
215
```typescript { .api }
216
/**
217
* Hook to run effects when screen gains/loses focus
218
* @param effect - Memoized callback containing the effect logic
219
*/
220
function useFocusEffect(effect: () => undefined | void | (() => void)): void;
221
```
222
223
**Usage Examples:**
224
225
```typescript
226
import React from 'react';
227
import { useFocusEffect } from "@react-navigation/core";
228
229
function DataScreen() {
230
const [data, setData] = useState(null);
231
232
useFocusEffect(
233
React.useCallback(() => {
234
// Effect runs when screen comes into focus
235
console.log('Screen focused, loading data...');
236
237
const fetchData = async () => {
238
const result = await api.getData();
239
setData(result);
240
};
241
242
fetchData();
243
244
// Cleanup function runs when screen loses focus
245
return () => {
246
console.log('Screen unfocused, cleaning up...');
247
setData(null);
248
};
249
}, []) // Empty dependency array
250
);
251
252
return (
253
<View>
254
{data ? <DataView data={data} /> : <LoadingView />}
255
</View>
256
);
257
}
258
259
// Managing subscriptions
260
function ChatScreen() {
261
useFocusEffect(
262
React.useCallback(() => {
263
const subscription = chatService.subscribe(handleMessage);
264
265
return () => subscription.unsubscribe();
266
}, [])
267
);
268
}
269
```
270
271
### useNavigationState
272
273
Hook to get a specific value from the current navigation state using a selector function.
274
275
```typescript { .api }
276
/**
277
* Hook to select a value from navigation state
278
* @param selector - Function to extract value from navigation state
279
* @returns Selected value from navigation state
280
*/
281
function useNavigationState<T>(
282
selector: (state: NavigationState) => T
283
): T;
284
```
285
286
**Usage Examples:**
287
288
```typescript
289
import { useNavigationState } from "@react-navigation/core";
290
291
function NavigationInfo() {
292
// Get current route index
293
const routeIndex = useNavigationState(state => state.index);
294
295
// Get all route names
296
const routeNames = useNavigationState(state =>
297
state.routes.map(route => route.name)
298
);
299
300
// Get history length
301
const historyLength = useNavigationState(state => state.routes.length);
302
303
return (
304
<View>
305
<Text>Current Index: {routeIndex}</Text>
306
<Text>Routes: {routeNames.join(', ')}</Text>
307
<Text>History: {historyLength}</Text>
308
</View>
309
);
310
}
311
```
312
313
### usePreventRemove
314
315
Hook to prevent the screen from being removed or navigated away from.
316
317
```typescript { .api }
318
/**
319
* Hook to prevent screen removal under certain conditions
320
* @param preventRemove - Boolean indicating whether to prevent removal
321
* @param callback - Function called when removal is attempted while prevented
322
*/
323
function usePreventRemove(
324
preventRemove: boolean,
325
callback: (data: { action: NavigationAction }) => void
326
): void;
327
```
328
329
**Usage Examples:**
330
331
```typescript
332
import { usePreventRemove } from "@react-navigation/core";
333
import { Alert } from 'react-native';
334
335
function EditProfileScreen() {
336
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
337
338
usePreventRemove(hasUnsavedChanges, ({ data }) => {
339
Alert.alert(
340
'Discard changes?',
341
'You have unsaved changes. Are you sure to discard them and leave the screen?',
342
[
343
{ text: "Don't leave", style: 'cancel' },
344
{
345
text: 'Discard',
346
style: 'destructive',
347
onPress: () => {
348
setHasUnsavedChanges(false);
349
// Navigate after removing prevention
350
navigation.dispatch(data.action);
351
},
352
},
353
]
354
);
355
});
356
357
return (
358
<View>
359
<TextInput
360
onChangeText={() => setHasUnsavedChanges(true)}
361
placeholder="Edit profile..."
362
/>
363
<Button
364
title="Save"
365
onPress={() => {
366
// Save logic
367
setHasUnsavedChanges(false);
368
}}
369
/>
370
</View>
371
);
372
}
373
```
374
375
### useNavigationBuilder
376
377
Advanced hook for building custom navigators. Handles state management, route configurations, and event handling.
378
379
```typescript { .api }
380
/**
381
* Core hook for building custom navigators
382
* @param createRouter - Function that creates the router
383
* @param options - Navigator options and configuration
384
* @returns Navigation builder utilities and state
385
*/
386
function useNavigationBuilder<
387
State extends NavigationState,
388
ScreenOptions extends {},
389
EventMap extends EventMapBase,
390
Navigation
391
>(
392
createRouter: RouterFactory<State, any, any>,
393
options: DefaultNavigatorOptions<any, any, State, ScreenOptions, EventMap, Navigation>
394
): {
395
state: State;
396
navigation: Navigation;
397
descriptors: Record<string, Descriptor<ScreenOptions, Navigation, RouteProp<any>>>;
398
NavigationContent: React.ComponentType<{ children: React.ReactNode }>;
399
};
400
```
401
402
**Usage Example:**
403
404
```typescript
405
import { useNavigationBuilder, createNavigatorFactory } from "@react-navigation/core";
406
import { StackRouter } from "@react-navigation/routers";
407
408
function CustomNavigator({ initialRouteName, children, ...rest }) {
409
const { state, navigation, descriptors, NavigationContent } = useNavigationBuilder(
410
StackRouter,
411
{
412
children,
413
initialRouteName,
414
...rest,
415
}
416
);
417
418
return (
419
<NavigationContent>
420
<View style={{ flex: 1 }}>
421
{state.routes.map((route) => {
422
const descriptor = descriptors[route.key];
423
const isFocused = state.index === state.routes.indexOf(route);
424
425
return (
426
<div key={route.key} style={{ display: isFocused ? 'block' : 'none' }}>
427
{descriptor.render()}
428
</div>
429
);
430
})}
431
</View>
432
</NavigationContent>
433
);
434
}
435
436
export default createNavigatorFactory(CustomNavigator);
437
```
438
439
### useTheme
440
441
Hook to access the current theme object.
442
443
```typescript { .api }
444
/**
445
* Hook to access the current theme
446
* @returns Theme object with colors and styling properties
447
*/
448
function useTheme(): ReactNavigation.Theme;
449
450
interface Theme {
451
dark: boolean;
452
colors: {
453
primary: string;
454
background: string;
455
card: string;
456
text: string;
457
border: string;
458
notification: string;
459
};
460
}
461
```
462
463
**Usage Examples:**
464
465
```typescript
466
import { useTheme } from "@react-navigation/core";
467
468
function ThemedComponent() {
469
const theme = useTheme();
470
471
return (
472
<View style={{ backgroundColor: theme.colors.background }}>
473
<Text style={{ color: theme.colors.text }}>
474
Themed text
475
</Text>
476
<View style={{
477
borderColor: theme.colors.border,
478
backgroundColor: theme.colors.card
479
}}>
480
Card content
481
</View>
482
</View>
483
);
484
}
485
```
486
487
### useNavigationContainerRef
488
489
Hook to create a navigation container ref for programmatic navigation control.
490
491
```typescript { .api }
492
/**
493
* Hook to create a navigation container ref
494
* @returns Navigation container ref object
495
*/
496
function useNavigationContainerRef<ParamList extends ParamListBase>(): NavigationContainerRef<ParamList>;
497
498
interface NavigationContainerRef<ParamList extends ParamListBase> {
499
/** Navigate to a route */
500
navigate<RouteName extends keyof ParamList>(
501
name: RouteName,
502
params?: ParamList[RouteName]
503
): void;
504
/** Go back */
505
goBack(): void;
506
/** Dispatch navigation action */
507
dispatch(action: NavigationAction): void;
508
/** Reset navigation state */
509
reset(state: PartialState<NavigationState> | NavigationState): void;
510
/** Get current navigation state */
511
getState(): NavigationState | undefined;
512
/** Check if navigator is ready */
513
isReady(): boolean;
514
/** Get current route */
515
getCurrentRoute(): Route<string> | undefined;
516
/** Get current options */
517
getCurrentOptions(): object | undefined;
518
}
519
```
520
521
**Usage Examples:**
522
523
```typescript
524
import { useNavigationContainerRef } from "@react-navigation/core";
525
526
function App() {
527
const navigationRef = useNavigationContainerRef();
528
529
// Navigate programmatically from outside component tree
530
const handleDeepLink = (url: string) => {
531
if (navigationRef.isReady()) {
532
navigationRef.navigate('Profile', { userId: extractUserId(url) });
533
}
534
};
535
536
return (
537
<NavigationContainer ref={navigationRef}>
538
<Stack.Navigator>
539
<Stack.Screen name="Home" component={HomeScreen} />
540
<Stack.Screen name="Profile" component={ProfileScreen} />
541
</Stack.Navigator>
542
</NavigationContainer>
543
);
544
}
545
```
546
547
### usePreventRemoveContext
548
549
Hook to access the prevent remove context state.
550
551
```typescript { .api }
552
/**
553
* Hook to access prevent remove context
554
* @returns Prevent remove context state
555
*/
556
function usePreventRemoveContext(): {
557
preventRemove: boolean;
558
};
559
```
560
561
### useNavigationIndependentTree
562
563
Hook to create an independent navigation tree context.
564
565
```typescript { .api }
566
/**
567
* Hook for independent navigation tree context
568
* @returns Independent tree context
569
*/
570
function useNavigationIndependentTree(): React.Context<boolean | undefined>;
571
```
572
573
### useStateForPath
574
575
Hook to get minimal navigation state for building paths.
576
577
```typescript { .api }
578
/**
579
* Hook to get minimal state for path building
580
* @returns State for path generation
581
*/
582
function useStateForPath(): NavigationState | PartialState<NavigationState> | undefined;
583
```