React Native Navigation Pattern: Global Stack for Shared Screens
React Native Navigation Pattern: Global Stack for Shared Screens
In many React Native apps, you’ll want to open a screen (like an Article or Details page) from multiple tabs, and have the back button return to the correct previous tab. If you simply nest your screen inside a stack for one tab, you’ll run into a common UX issue: the back button always returns to the root of that stack, not to the tab you came from.
The Problem
Suppose you have a tab navigator with Home, Study, and Mastery tabs. If you put ArticleScreen inside the Home stack, and navigate to it from Study or Mastery, the back button will always return to Home—not the tab you came from. This is because the navigation stack is local to the tab.
The Solution: Use a Global Stack
The best practice is to create a RootStack that wraps your tab navigator and any shared screens. This way, any tab can push the shared screen, and the back button will return to the correct previous tab.
Step 1: Define the Root Stack
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import TabNavigator from './TabNavigator';
import ArticleScreen from './ArticleScreen';
const RootStack = createNativeStackNavigator();
export default function AppNavigator() {
return (
<RootStack.Navigator>
<RootStack.Screen
name="Main"
component={TabNavigator}
options={{ headerShown: false }}
/>
<RootStack.Screen
name="Article"
component={ArticleScreen}
options={{ title: 'Article' }}
/>
</RootStack.Navigator>
);
}
Step 2: Remove ArticleScreen from Tab Stacks
Only include ArticleScreen in the RootStack, not in any tab’s stack.
Step 3: Update Navigation Calls
When you want to open the Article screen from any tab, use:
navigation.navigate('Article', { articleId });
Now, when you press the back button, you’ll return to the correct tab, preserving the user’s context.
Why This Pattern Works
- It keeps your navigation history global, not local to a tab.
- It allows any tab to push shared screens, with correct back navigation.
- It’s scalable for any number of shared screens.
Conclusion
If you need to open a screen from multiple tabs and want the back button to work intuitively, use a global stack navigator. This pattern is clean, scalable, and provides the best user experience in React Native apps.
Have you used this pattern in your apps? Share your experience in the comments!
❤️ Support This Blog
If this post helped you, you can support my writing with a small donation. Thank you for reading.
Comments
Post a Comment