Home > OS >  which function is called when screen is returned from other screen in react native?
which function is called when screen is returned from other screen in react native?

Time:05-19

I can see the React native component life cycle. componentDidMount, UNSAFE_componentWillMount, etc I thought UNSAFE_componentWillMount is called when screen is resumed. But it is not called. I use React 17 over, React Native 0.68.1, and I use navigation.goBack() to return from second screen to first screen. Which function is called when screen is resumed? Or what other way to do that?

CodePudding user response:

In react native when you change screen and come back to the previous screen it doesn't rerenders so using useEffect hook doesen't work. However you can use useFocusEffect hook provided by the react navigation. You can read more in details Here

CodePudding user response:

You need to be careful here. In react-native a screen remains mounted on navigation. This differs from the web.

If you are coming to react-navigation from a web background, you may assume that when user navigates from route A to route B, A will unmount (its componentWillUnmount is called) and A will mount again when user comes back to it. While these React lifecycle methods are still valid and are used in react-navigation, their usage differs from the web.

Hence, if you navigate via goBack, the componentWillMount will not be called again, since the screen remains mounted. There is a general workaround for this problem which is documented here in the React Navigation lifecycle events section.

For functional components, we can use the useFocusEffect hook as follows.

useFocusEffect(
    React.useCallback(() => {
      // Do something when the screen is focused

      return () => {
        // Do something when the screen is unfocused
        // Useful for cleanup functions
      };
    }, [])
  );

For class components, we can use a focus listener. This is documented here.

class SomeClassComponent extends React.Component {
  componentDidMount() {
    this._unsubscribe = navigation.addListener('focus', () => {
      // do whatever
    });
  }

  componentWillUnmount() {
    this._unsubscribe();
  }

...

In some cases it might be more convenient to still use functional components. We can simply wrap a legacy class component into a functional component as follows.

const Wrapper = () => {
  // useFocusEffect from above.

  return <SomeClassComponent />
}
  • Related