'How to unmount screen on blur in a StackNavigator?
Im using React Navigation x5, I have StackNavigator that's loading bunch of screens. I want to unmount one particular screen component on blur to get the same result of using unmountOnBlur when using a DrawerNavigator.
How can I achieve that?
Solution 1:[1]
There are currently three ways to do it since 5.x. You can either
- use
useFocusEffecthook to trigger an action (recommended), or - use
useIsFocusedhook, or - listen to the
focusevent
Example of useFocusEffect
import { useFocusEffect } from '@react-navigation/native';
function Sample(props) {
const [shouldHide, setShouldHide] = React.useState(false);
useFocusEffect(() => {
setShouldHide(false)
return () => {
setShouldHide(true)
}
});
return shouldHide ? null : <InnerComponent {...props} />;
}
Example of useIsFocused hook
import * as React from 'react';
import { Text } from 'react-native';
import { useIsFocused } from '@react-navigation/native';
function Profile() {
// This hook returns `true` if the screen is focused, `false` otherwise
const isFocused = useIsFocused();
return {isFocused ? <Text>Inner component</Text> : null};
}
Note:
Using this hook component may introduce unnecessary component re-renders as a screen comes in and out of focus. ... Hence we recommend to use this hook only if you need to trigger a re-render.
More information can be found in the documentation Call a function when focused screen changes
Besides that, stack navigators come with a prop called detachInactiveScreens which is enabled by default. Link to the documentation
Boolean used to indicate whether inactive screens should be detached from the view hierarchy to save memory. Make sure to call
enableScreensfromreact-native-screensto make it work. Defaults totrue.
(The instruction on enabling React Native Screens can be found at https://reactnavigation.org/docs/react-native-screens/#setup-when-you-are-using-expo)
Inside the stack navigator's options object, there is also a detachPreviousScreen prop to customise the behaviour of certain screens. This option is usually enabled as well.
Boolean used to indicate whether to detach the previous screen from the view hierarchy to save memory. Set it to
falseif you need the previous screen to be seen through the active screen. Only applicable ifdetachInactiveScreensisn't set to false. Defaults tofalsefor the last screen whenmode='modal', otherwisetrue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
