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?
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?
There are currently three ways to do it since 5.x
. You can either
useFocusEffect
hook to trigger an action (recommended), oruseIsFocused
hook, orfocus
eventuseFocusEffect
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} />;
}
useIsFocused
hookimport * 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
enableScreens
fromreact-native-screens
to 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
false
if you need the previous screen to be seen through the active screen. Only applicable ifdetachInactiveScreens
isn't set to false. Defaults tofalse
for the last screen whenmode='modal'
, otherwisetrue
.