Stack Navigator Deep Dive
The stack navigator is the most commonly used navigator in React Native. It works like a stack of cards — you push screens onto the stack when navigating forward and pop them off when going back. Every new screen slides in from the right (or bottom on iOS) and slides back out when you go back.
Stack navigation is perfect for flows like: Login → Home → Profile → Settings, where each screen leads to the next in a linear sequence.
Passing Data Between Screens
One of the most common needs is passing data from one screen to another. React Navigation makes this easy with the params option.
function HomeScreen({ navigation }) {
return (
<View>
<Button
title="Go to Profile"
onPress={() => navigation.navigate('Profile', {
userName: 'John',
userId: 123,
})}
/>
</View>
);
}
function ProfileScreen({ route }) {
const { userName, userId } = route.params;
return (
<View>
<Text>Hello, {userName}!</Text>
<Text>User ID: {userId}</Text>
</View>
);
}
When navigating, pass an object as the second argument to navigate. On the receiving screen, access these values through route.params. This is how you share data between screens without global state.
Configuring the Stack
You can customize the stack's appearance and behavior through the navigator's options and screen options.
<Stack.Navigator
initialRouteName="Home"
screenOptions={{
headerStyle: { backgroundColor: '#2196F3' },
headerTintColor: '#fff',
headerTitleStyle: { fontWeight: 'bold' },
}}
>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'My Home' }}
/>
<Stack.Screen
name="Details"
component={DetailsScreen}
options={({ route }) => ({
title: route.params?.itemName || 'Details',
})}
/>
</Stack.Navigator>
The screenOptions apply to all screens in the stack. Individual screens can override these with their own options prop. You can also use a function for options to access the route params and set dynamic titles.
Navigation Actions
The navigation object provides several methods to control the stack:
// Push a new screen (allows duplicates)
navigation.push('Details');
// Navigate to a screen (reuses if it exists)
navigation.navigate('Details');
// Go back to the previous screen
navigation.goBack();
// Go back to the first screen in the stack
navigation.popToTop();
// Replace the current screen instead of pushing
navigation.replace('Details');
Use navigate for most cases. Use push when you need to open the same screen multiple times (like viewing different user profiles). Use replace when you want to swap the current screen without adding to the back stack (like after login, replacing login with home).