Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the hook that helps save navigation state.
React Native
import { [1] } from '@react-navigation/native';
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a hook that does not exist in the library.
Confusing navigation state hooks with navigation container refs.
✗ Incorrect
The hook useNavigationContainerRef is used to create a ref to the navigation container, which helps in persisting navigation state.
2fill in blank
mediumComplete the code to load the saved navigation state from async storage.
React Native
const loadState = async () => {
const savedState = await AsyncStorage.[1]('NAVIGATION_STATE');
if (savedState) {
setInitialState(JSON.parse(savedState));
}
}; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using setItem instead of getItem to read data.
Trying to remove or clear storage instead of reading.
✗ Incorrect
AsyncStorage.getItem is used to retrieve a saved value by key.
3fill in blank
hardFix the error in saving the navigation state when it changes.
React Native
const onStateChange = (state) => {
AsyncStorage.[1]('NAVIGATION_STATE', JSON.stringify(state));
}; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using getItem instead of setItem to save data.
Not converting state to a string before saving.
✗ Incorrect
To save data to AsyncStorage, use setItem with a key and string value.
4fill in blank
hardFill both blanks to correctly initialize navigation container with persistence.
React Native
const navigationRef = [1](); <NavigationContainer ref={navigationRef} initialState={initialState} onStateChange={onStateChange} >[2]</NavigationContainer>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using useState instead of useNavigationContainerRef for the ref.
Placing no navigator or wrong navigator inside NavigationContainer.
✗ Incorrect
useNavigationContainerRef creates the ref for navigation container. The StackNavigator component is placed inside NavigationContainer to define screens.
5fill in blank
hardFill all three blanks to complete the async effect that loads saved navigation state on app start.
React Native
useEffect(() => {
const restoreState = async () => {
const savedState = await AsyncStorage.[1]('NAVIGATION_STATE');
if (savedState) {
setInitialState(JSON.[2](savedState));
}
setIsReady(true);
};
if (!isReady) {
restoreState();
}
}, [[3]]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using setItem instead of getItem to read data.
Using JSON.stringify instead of JSON.parse to convert data.
Leaving dependency array empty causing multiple runs.
✗ Incorrect
getItem reads the saved state, JSON.parse converts it back to an object, and isReady is the dependency to run effect only once.