7

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?

abdou-tech
  • 687
  • 1
  • 8
  • 16

1 Answers1

8

There are currently three ways to do it since 5.x. You can either

  • use useFocusEffect hook to trigger an action (recommended), or
  • use useIsFocused hook, or
  • listen to the focus event
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

detachInactiveScreens

Boolean used to indicate whether inactive screens should be detached from the view hierarchy to save memory. Make sure to call enableScreens from react-native-screens to make it work. Defaults to true.

(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.

detachPreviousScreen

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 if detachInactiveScreens isn't set to false. Defaults to false for the last screen when mode='modal', otherwise true.

Tyson Z
  • 338
  • 1
  • 5