Search code examples
react-navigationreact-navigation-v5

How to trigger useEffect when passing props back to parent component


This question is for React Navigation 5 in React Native app. When passing a props back to parent screen, how to setup trigger in parent screen for useEffect? Here is an example:

Child Screen

_onPress = (country, country_code, calling_code) => {
    const { navigation, route } = this.props;
    navigation.navigate("parent"
    {select:{
        country_name: country,
        country_code: country_code,
        calling_code: calling_code
    });
};

on parent component. useEffect is used to do something after the props select is passed back from the child screen:

useEffect(()=> {
   if (route.params?.select?) {
      //do something after select is passed back
   }
}, [what is the trigger?])  //<<==how to setup trigger for useEffect?. [] did not work.

How to setup trigger in parent component for useEffect? Tried to use [] which shall trigger with any reload but it did not work. Shall the same props select be passed from parent component to child screen and passed back to parent component again after being updated in child screen? Is select a trigger?


Solution

  • Well, since you are using React Navigation 5, what you can do is to replace useEffect with useFocusEffect, and your functions will be called every time when the user arrives/returns to the parent screen.

    First import useFocusEffect at the top of your file like this:

    import { useFocusEffect } from "@react-navigation/native"

    then replace useEffect with useFocusEffect like this:

     useFocusEffect(
        React.useCallback(() => {
          if (route.params?.select?) {
          //do something after select is passed back
       }
          return () => {
            // Here you can do something when the screen is unfocused such as clearing event listners but you can also leave it empty if you want
           
          };
        }, [])
      );