Search code examples
react-nativenavigation

How to call a function once the back button is clicked in recact native


After i do navigation.goBack(); to go back to a page i want to run a function, how can i do that?, NOTE: if i am redirecting from pageA to pageB, i want to run the function once i get to pageB, and i also want to solve for going back with the physical back button

This is what i have tried:

 <TouchableOpacity
     onPress={() => {
     navigation.goBack();
     }}>
     <Ionicons
     name="chevron-back-outline"
     size={24}
     color="#000"
     style={{}}
   />
 </TouchableOpacity>
//this is pageA


  useEffect(()=>{
    getUserInfo()
  })
//on pageB

Solution

  • Great question, for this purpose you can use the useFocusEffect this hook runs once every time you focus again on a view allowing yo to execute some code just after the goBack function takes effect.

    import { useFocusEffect } from '@react-navigation/native';
    
    const PageB = () => {
      // ... other code for pageB
      useFocusEffect(
        React.useCallback(() => {
          getUserInfo();
          // Return a cleanup function if necessary
          return () => {
            // Cleanup code (if needed)
          };
        }, [])
      );
    };
    
    

    Intercepting Backbutton event:

    With this purpose, you can simply use the BackHandler event listener:

    import { BackHandler } from 'react-native';
    
    useEffect(() => {
      const backAction = () => {
        getUserInfo();
        return true;  // Prevent default behavior (optional)
      };
    
      const backHandler = BackHandler.addEventListener(
        'hardwareBackPress',
        backAction
      );
    
      return () => backHandler.remove();
    }, []);
    

    I Hope it works for you!