Home > Back-end >  EXPO useEffect not called on navigating to same screen
EXPO useEffect not called on navigating to same screen

Time:05-10

I have one screen which called useEffect when rendered first time in the flow. The second time I navigate to the screen in the flow , use Effect is not called but I want to call a function upon first time before , after or during render function is called when we navigate a second time to the same screen.

Here is the navigate call for everytime navigating to this screen from various screens

navigation.navigate("x", { u:type, s:title});

The following is the structure for my screen. I am not using components but functions with navigation

const x = ({ navigation}) => {
    ...
   return (
    <View style={styles.a}>
            ...    
   </View>
  );
};

export default x;

CodePudding user response:

The problem here is that a screen remains mounted in react-native after the initial navigation. Thus, a useEffect with an empty dependency array won't be called subsequently on navigation.

Notice that this behavior 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.

The recommended way to solve this is described here. For your case this can be solved as follows.

import { useFocusEffect } from '@react-navigation/native';

const x = ({ navigation}) => {
    
   useFocusEffect(
     React.useCallback(() => {
      // called when screen is focused, thus everytime on navigation
      return () => {
        // unfocus... cleanup ... or whatever
      };
    }, [])
  );

   ...

   return (
    <View style={styles.a}>
            ...    
   </View>
  );
};

export default x;

CodePudding user response:

useEffect will be called on first load of your functional component or when some dependency will be changed. Everything remains the same, so your useEffect will not work. Consider using useFocusEffect from react-navigation lib instead.

  • Related