Core utilities for building navigators in React Native applications
—
Core hooks for accessing navigation functionality from anywhere in the component tree, providing navigation methods, route information, screen lifecycle management, and navigation state access.
Hook to access the navigation prop of the parent screen from any component in the tree.
/**
* Hook to access navigation functionality from any component
* @returns Navigation object with methods for navigation control
*/
function useNavigation<T = NavigationProp<ParamListBase>>(): T;
interface NavigationProp<ParamList extends ParamListBase = ParamListBase> {
/** Navigate to a screen by name with optional parameters */
navigate<RouteName extends keyof ParamList>(
name: RouteName,
params?: ParamList[RouteName]
): void;
/** Navigate to a screen with detailed options */
navigate<RouteName extends keyof ParamList>(options: {
name: RouteName;
params?: ParamList[RouteName];
merge?: boolean;
pop?: boolean;
}): void;
/** Go back to the previous screen */
goBack(): void;
/** Dispatch a navigation action */
dispatch(action: NavigationAction | ((state: NavigationState) => NavigationAction)): void;
/** Update screen options */
setOptions(options: Partial<ScreenOptions>): void;
/** Check if the current screen is focused */
isFocused(): boolean;
/** Check if navigation can go back */
canGoBack(): boolean;
/** Get the current navigation state */
getState(): NavigationState;
/** Get parent navigator by optional ID */
getParent<T = NavigationProp<ParamListBase> | undefined>(id?: string): T;
/** Update route parameters */
setParams(params: Partial<ParamList[keyof ParamList]>): void;
/** Reset navigation state */
reset(state: PartialState<NavigationState> | NavigationState): void;
/** Get navigator ID */
getId(): string | undefined;
/** Preload a screen */
preload<RouteName extends keyof ParamList>(
name: RouteName,
params?: ParamList[RouteName]
): void;
}Usage Examples:
import { useNavigation } from "@react-navigation/core";
function MyComponent() {
const navigation = useNavigation();
const handleNavigate = () => {
// Navigate to a screen
navigation.navigate('Profile', { userId: '123' });
// Navigate with options
navigation.navigate({
name: 'Profile',
params: { userId: '123' },
merge: true
});
};
const handleGoBack = () => {
if (navigation.canGoBack()) {
navigation.goBack();
}
};
return (
<View>
<Button title="Go to Profile" onPress={handleNavigate} />
<Button title="Go Back" onPress={handleGoBack} />
</View>
);
}Hook to access the route prop of the parent screen from any component in the tree.
/**
* Hook to access current route information
* @returns Route object containing name, key, params, and path
*/
function useRoute<T = RouteProp<ParamListBase>>(): T;
interface RouteProp<
ParamList extends ParamListBase = ParamListBase,
RouteName extends keyof ParamList = keyof ParamList
> {
/** Unique route identifier */
key: string;
/** Route name */
name: RouteName;
/** Route parameters */
params: ParamList[RouteName];
/** Optional path for deep linking */
path?: string;
/** Optional nested navigation state */
state?: NavigationState | PartialState<NavigationState>;
}Usage Examples:
import { useRoute } from "@react-navigation/core";
function ProfileScreen() {
const route = useRoute();
return (
<View>
<Text>Screen: {route.name}</Text>
<Text>User ID: {route.params?.userId}</Text>
<Text>Route Key: {route.key}</Text>
</View>
);
}
// Type-safe usage with proper param typing
type RootParamList = {
Profile: { userId: string; tab?: string };
Settings: undefined;
};
function TypedProfileScreen() {
const route = useRoute<RouteProp<RootParamList, 'Profile'>>();
// route.params is now properly typed
const { userId, tab } = route.params;
return (
<View>
<Text>User: {userId}</Text>
{tab && <Text>Tab: {tab}</Text>}
</View>
);
}Hook to get the current focus state of the screen. Returns true if the screen is focused, false otherwise.
/**
* Hook to check if the current screen is focused
* @returns Boolean indicating focus state
*/
function useIsFocused(): boolean;Usage Examples:
import { useIsFocused } from "@react-navigation/core";
function MyScreen() {
const isFocused = useIsFocused();
// Conditionally render based on focus
if (!isFocused) {
return <View><Text>Screen is not focused</Text></View>;
}
return (
<View>
<Text>Screen is focused!</Text>
<StatusBar barStyle="dark-content" />
</View>
);
}
// Using with effects
function TimerScreen() {
const isFocused = useIsFocused();
const [count, setCount] = useState(0);
useEffect(() => {
let interval;
if (isFocused) {
interval = setInterval(() => {
setCount(c => c + 1);
}, 1000);
}
return () => clearInterval(interval);
}, [isFocused]);
return <Text>Count: {count}</Text>;
}Hook to run side effects when screen comes into focus, similar to useEffect but focus-aware.
/**
* Hook to run effects when screen gains/loses focus
* @param effect - Memoized callback containing the effect logic
*/
function useFocusEffect(effect: () => undefined | void | (() => void)): void;Usage Examples:
import React from 'react';
import { useFocusEffect } from "@react-navigation/core";
function DataScreen() {
const [data, setData] = useState(null);
useFocusEffect(
React.useCallback(() => {
// Effect runs when screen comes into focus
console.log('Screen focused, loading data...');
const fetchData = async () => {
const result = await api.getData();
setData(result);
};
fetchData();
// Cleanup function runs when screen loses focus
return () => {
console.log('Screen unfocused, cleaning up...');
setData(null);
};
}, []) // Empty dependency array
);
return (
<View>
{data ? <DataView data={data} /> : <LoadingView />}
</View>
);
}
// Managing subscriptions
function ChatScreen() {
useFocusEffect(
React.useCallback(() => {
const subscription = chatService.subscribe(handleMessage);
return () => subscription.unsubscribe();
}, [])
);
}Hook to get a specific value from the current navigation state using a selector function.
/**
* Hook to select a value from navigation state
* @param selector - Function to extract value from navigation state
* @returns Selected value from navigation state
*/
function useNavigationState<T>(
selector: (state: NavigationState) => T
): T;Usage Examples:
import { useNavigationState } from "@react-navigation/core";
function NavigationInfo() {
// Get current route index
const routeIndex = useNavigationState(state => state.index);
// Get all route names
const routeNames = useNavigationState(state =>
state.routes.map(route => route.name)
);
// Get history length
const historyLength = useNavigationState(state => state.routes.length);
return (
<View>
<Text>Current Index: {routeIndex}</Text>
<Text>Routes: {routeNames.join(', ')}</Text>
<Text>History: {historyLength}</Text>
</View>
);
}Hook to prevent the screen from being removed or navigated away from.
/**
* Hook to prevent screen removal under certain conditions
* @param preventRemove - Boolean indicating whether to prevent removal
* @param callback - Function called when removal is attempted while prevented
*/
function usePreventRemove(
preventRemove: boolean,
callback: (data: { action: NavigationAction }) => void
): void;Usage Examples:
import { usePreventRemove } from "@react-navigation/core";
import { Alert } from 'react-native';
function EditProfileScreen() {
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
usePreventRemove(hasUnsavedChanges, ({ data }) => {
Alert.alert(
'Discard changes?',
'You have unsaved changes. Are you sure to discard them and leave the screen?',
[
{ text: "Don't leave", style: 'cancel' },
{
text: 'Discard',
style: 'destructive',
onPress: () => {
setHasUnsavedChanges(false);
// Navigate after removing prevention
navigation.dispatch(data.action);
},
},
]
);
});
return (
<View>
<TextInput
onChangeText={() => setHasUnsavedChanges(true)}
placeholder="Edit profile..."
/>
<Button
title="Save"
onPress={() => {
// Save logic
setHasUnsavedChanges(false);
}}
/>
</View>
);
}Advanced hook for building custom navigators. Handles state management, route configurations, and event handling.
/**
* Core hook for building custom navigators
* @param createRouter - Function that creates the router
* @param options - Navigator options and configuration
* @returns Navigation builder utilities and state
*/
function useNavigationBuilder<
State extends NavigationState,
ScreenOptions extends {},
EventMap extends EventMapBase,
Navigation
>(
createRouter: RouterFactory<State, any, any>,
options: DefaultNavigatorOptions<any, any, State, ScreenOptions, EventMap, Navigation>
): {
state: State;
navigation: Navigation;
descriptors: Record<string, Descriptor<ScreenOptions, Navigation, RouteProp<any>>>;
NavigationContent: React.ComponentType<{ children: React.ReactNode }>;
};Usage Example:
import { useNavigationBuilder, createNavigatorFactory } from "@react-navigation/core";
import { StackRouter } from "@react-navigation/routers";
function CustomNavigator({ initialRouteName, children, ...rest }) {
const { state, navigation, descriptors, NavigationContent } = useNavigationBuilder(
StackRouter,
{
children,
initialRouteName,
...rest,
}
);
return (
<NavigationContent>
<View style={{ flex: 1 }}>
{state.routes.map((route) => {
const descriptor = descriptors[route.key];
const isFocused = state.index === state.routes.indexOf(route);
return (
<div key={route.key} style={{ display: isFocused ? 'block' : 'none' }}>
{descriptor.render()}
</div>
);
})}
</View>
</NavigationContent>
);
}
export default createNavigatorFactory(CustomNavigator);Hook to access the current theme object.
/**
* Hook to access the current theme
* @returns Theme object with colors and styling properties
*/
function useTheme(): ReactNavigation.Theme;
interface Theme {
dark: boolean;
colors: {
primary: string;
background: string;
card: string;
text: string;
border: string;
notification: string;
};
}Usage Examples:
import { useTheme } from "@react-navigation/core";
function ThemedComponent() {
const theme = useTheme();
return (
<View style={{ backgroundColor: theme.colors.background }}>
<Text style={{ color: theme.colors.text }}>
Themed text
</Text>
<View style={{
borderColor: theme.colors.border,
backgroundColor: theme.colors.card
}}>
Card content
</View>
</View>
);
}Hook to create a navigation container ref for programmatic navigation control.
/**
* Hook to create a navigation container ref
* @returns Navigation container ref object
*/
function useNavigationContainerRef<ParamList extends ParamListBase>(): NavigationContainerRef<ParamList>;
interface NavigationContainerRef<ParamList extends ParamListBase> {
/** Navigate to a route */
navigate<RouteName extends keyof ParamList>(
name: RouteName,
params?: ParamList[RouteName]
): void;
/** Go back */
goBack(): void;
/** Dispatch navigation action */
dispatch(action: NavigationAction): void;
/** Reset navigation state */
reset(state: PartialState<NavigationState> | NavigationState): void;
/** Get current navigation state */
getState(): NavigationState | undefined;
/** Check if navigator is ready */
isReady(): boolean;
/** Get current route */
getCurrentRoute(): Route<string> | undefined;
/** Get current options */
getCurrentOptions(): object | undefined;
}Usage Examples:
import { useNavigationContainerRef } from "@react-navigation/core";
function App() {
const navigationRef = useNavigationContainerRef();
// Navigate programmatically from outside component tree
const handleDeepLink = (url: string) => {
if (navigationRef.isReady()) {
navigationRef.navigate('Profile', { userId: extractUserId(url) });
}
};
return (
<NavigationContainer ref={navigationRef}>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Profile" component={ProfileScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}Hook to access the prevent remove context state.
/**
* Hook to access prevent remove context
* @returns Prevent remove context state
*/
function usePreventRemoveContext(): {
preventRemove: boolean;
};Hook to create an independent navigation tree context.
/**
* Hook for independent navigation tree context
* @returns Independent tree context
*/
function useNavigationIndependentTree(): React.Context<boolean | undefined>;Hook to get minimal navigation state for building paths.
/**
* Hook to get minimal state for path building
* @returns State for path generation
*/
function useStateForPath(): NavigationState | PartialState<NavigationState> | undefined;Install with Tessl CLI
npx tessl i tessl/npm-react-navigation--core