Consider a React Native app using React Navigation with state persistence enabled. The user navigates from Home to Profile screen. Then the app is closed and reopened.
What will be the visible screen after reopening?
Think about what state persistence means for navigation.
When navigation state persistence is enabled, the app saves the current navigation stack. On restart, it restores this stack, so the user returns to the last visited screen.
In React Navigation, to persist navigation state, which method is typically used to save the state externally?
Look for a callback that triggers when navigation state changes.
The onStateChange prop on the NavigationContainer is called whenever navigation state changes. This is where you save the state to persistent storage.
Given this code snippet for restoring navigation state in React Native:
const [isReady, setIsReady] = React.useState(false);
const [initialState, setInitialState] = React.useState();
React.useEffect(() => {
async function restoreState() {
const savedState = await AsyncStorage.getItem('NAVIGATION_STATE');
if (savedState) {
setInitialState(JSON.parse(savedState));
}
setIsReady(true);
}
restoreState();
}, []);
if (!isReady) {
return null;
}
return (
<NavigationContainer initialState={initialState} onStateChange={...} >...
);What is a common reason this restoration might silently fail and show the initial screen instead of the saved state?
Think about when NavigationContainer reads the initialState prop.
NavigationContainer reads the initialState only on first mount. If initialState is undefined at that time and set later, it will ignore it and start fresh.
If the saved navigation state in AsyncStorage is corrupted or incomplete JSON, what error will React Navigation most likely throw when trying to restore it?
Consider what happens when JSON.parse fails.
If the saved state is corrupted, JSON.parse throws a SyntaxError indicating invalid JSON syntax.
In a large React Native app with many screens, persisting the entire navigation state can be slow and cause UI delays. Which approach best optimizes navigation state persistence?
Think about saving less data to improve performance.
Saving only essential parts of the navigation state reduces storage size and speeds up restoration, improving app responsiveness.