Performing action on swipe back (react-navigation)

React Navigation 5.7 introduced a simple way to do this without the need to override back actions or swipe gestures, basically you intercept the back action in the component and execute a callback before it happens:

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

const MyScreenComponent = (props) => {
  const navigation = useNavigation();

  React.useEffect(() => (
    navigation.addListener('beforeRemove', (e) => {
      // Prevent default behavior of leaving the screen (if needed)
      e.preventDefault();

      // Do whatever...
    })
  ), [navigation]);

  // Rest of component
}

In this example I'm using the useNavigation hook to access the navigation object, but you can also extract it from the props, it really depends on how your app is built.

Official documentation.


I was able to determine whether the app is going back via the back button or swiping back with the getStateForAction function of the router. Play around with checking the action and state variables to fine tune it more if needed.

export const ScreensStack = StackNavigator(
{
    Login: {screen: LoginScreen},
    Schedule: {screen: ScheduleScreen},
}

/**
 * Intercept actions occuring in the screen stack.
 */
const getStateForActionScreensStack = ScreensStack.router.getStateForAction;

ScreensStack.router = {
    ...ScreensStack.router,
    getStateForAction(action, state) {
      if (action.type == 'Navigation/BACK') {
        console.log('We are going back...');
      }
      return getStateForActionScreensStack(action, state);
    },
};