React navigation useBackButton example

Here is an example of how you might use the useBackButton hook in a React Native app that uses React Navigation:

import { useBackButton } from 'react-navigation-hooks';

export default function MyScreen() {
  useBackButton(() => {
    // Do something when the back button is pressed
    // (such as navigating to the previous screen)
    navigation.goBack();
    return true; // Return true to prevent the default back button behavior
  });

  return (
    <View>
      {/* Your screen content goes here */}
    </View>
  );
}

In this example, the useBackButton hook is being used to specify a custom behavior for when the back button is pressed while the user is on the “MyScreen” screen. In this case, the navigation.goBack() method is used to navigate to the previous screen in the stack. Also, the return value true prevents the default back button behavior.

Please note that this example uses react-navigation-hooks package, which is a community-driven library for providing hooks for the various navigation functions in the react-navigation library.

react-navigation-hooks is depreciated

react-navigation-hooks is a depreciated package and you can use the hooks provided by the official react-navigation package instead.

Here is an example of how you might use the useFocusEffect hook in a React Native app that uses React Navigation:

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

export default function MyScreen({ navigation }) {
  useFocusEffect(
    React.useCallback(() => {
      const onBackPress = () => {
        // Do something when the back button is pressed
        // (such as navigating to the previous screen)
        navigation.goBack();
        return true; // Return true to prevent the default back button behavior
      };

      BackHandler.addEventListener('hardwareBackPress', onBackPress);

      return () =>
        BackHandler.removeEventListener('hardwareBackPress', onBackPress);
    }, [navigation])
  );

  return (
    <View>
      {/* Your screen content goes here */}
    </View>
  );
}

In this example, the useFocusEffect hook is being used to specify a custom behavior for when the back button is pressed while the user is on the “MyScreen” screen. In this case, the navigation.goBack() method is used to navigate to the previous screen in the stack. Also, the return value true prevent the default back button behavior. This example uses the BackHandler from ‘react-native’ to add and remove a listener for the ‘hardwareBackPress’ event.