To implement robust navigation patterns in React Native applications using Expo Router (recommended) or React Navigation.
- When the app has multiple screens.
- When needing tab bars, drawers, or stack navigation (push/pop).
- When handling deep links.
- Setup: Ensure
expo-routeris installed.npx expo install expo-router react-native-safe-area-context react-native-screens expo-linking expo-constants
- Structure:
app/index.tsx: The home screen.app/_layout.tsx: Defines the layout (Stack/Tabs).app/details/[id].tsx: Dynamic route.
- Implementation:
- Use
<Stack />or<Tabs />in_layout.tsx. - Navigate using
<Link href="/details/1">orrouter.push('/details/1').
- Use
- Install:
npm install @react_navigation/native @react_navigation/native-stack npx expo install react-native-screens react-native-safe-area-context
- Implementation:
import { NavigationContainer } from '@react_navigation/native'; import { createNativeStackNavigator } from '@react_navigation/native-stack'; const Stack = createNativeStackNavigator(); export default function App() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} /> <Stack.Screen name="Details" component={DetailsScreen} /> </Stack.Navigator> </NavigationContainer> ); }
- Type Safety: Always type routes for
useNavigationanduseRoutehooks to avoid runtime errors. - Nesting: Avoid deep nesting of navigators to prevent performance issues and state complexity.
A navigation structure allowing smooth transitions between screens, preserving history and state.