Menu Close

Double back button press to exit in React Native

double back press to exit

In this quick tutorial, we’ll be taking a look at how to implement double back press to exit, in React Native.

This is quite common functionality where apps require the user to press the back button twice (in Android) to exit the app. And this is also fairly straightforward to understand. 

We’ll make the use of BackHandler provided by React Native to handle back press events.

Adding BackHandler.addEventListener

To override the default back press we’ll use BackHandler.addEventListener

BackHandler.addEventListener("hardwareBackPress", onBackPress);

 

Note: The handler should be a parameterless function as expected by the API. Also, don’t forget to return true at the end of the handler so that React Native knows that the event has been handled.

 

The addEventListener method returns a NativeSubscription object which can later be used to remove the listener. Remember that removing the listener is necessary else the app will behave in unexpected ways. So, we’ll store the object in a const variable.

Creating the Handler

Let’s create the Handler to check for double back press. 

let currentCount = 0;
const onBackPress = () => {
  if (currentCount < 1) {
    currentCount += 1;
    WToast.show({
      data: "Press again to close!",
      duration: WToast.duration.SHORT,
    });
  } else {
    // exit the app here using BackHandler.exitApp();
  }
  setTimeout(() => {
    currentCount = 0;
  }, 2000);
};

What we do here is really simple: 

  1. When the user presses the back button.
  2. Check the current value. If it’s less than 1,
  3. Show a toast message asking the user to press it again. Increment the count.
  4. Use setTimeout to reset the counter to 0 if the user doesn’t press it again quickly. Here we have a timeout of 2 seconds.
  5. If it’s  === 1, then exit the app.

And this is all there is to implementing double back press to exit.

Improving the code further using Custom Hooks

The snippet above will work but what if you want to use it at multiple places. For example: double back press to close a popup/bottomscreen or any other important screen.

In that case, you’ll have to copy this everywhere. This will lead to redundant code and won’t be ideal. If you use an IDE such as WebStorm, it’ll alert you that you have redundant code.

So, to avoid this, I’ve created a custom hook. Custom hooks are nothing but functions with a fancy name. They usually begin with the ‘use’ keyword which helps the editor in lint checks etc.

Here is the custom hook with the handler: 

let currentCount = 0;
export const useDoubleBackPressExit = (
  exitHandler: () => void
) => {
  if (Platform.OS === "ios") return;
  const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
    if (currentCount === 1) {
      exitHandler();
      subscription.remove();
      return true;
    }
    backPressHandler();
    return true;
  });
};

const backPressHandler = () => {
  if (currentCount < 1) {
    currentCount += 1;
    WToast.show({
      data: "Press again to close!",
      duration: WToast.duration.SHORT,
    });
  }
  setTimeout(() => {
    currentCount = 0;
  }, 2000);
};

Note: Back press is possible only in Android so I’ve added a check here to ignore for iOS platforms.

 

In this, I’ve accepted a handler which will be called when the back button is pressed twice. You can do whatever you want here such as exit the app etc. 

And just after calling the handler, you should remove the subscription so that events continue to be handled by the system again instead of you.

This is just for double back press. You can accept a parameter indicating the number of times the back button should be pressed. Although it should rarely be > 2 unless you want the user to uninstall your app 😛

With this in place, you can use this code wherever you want with ease:

useDoubleBackPressExit(() => {
  // user has pressed "back" twice. Do whatever you want!
});

Would love to hear more suggestions on this and any improvements that can be done. Please mention it in the comments section below.

 

 

Welcome to AndroidVille 🙂

AndroidVille is a community of Mobile Developers where we share knowledge related to Android Development, Flutter Development, React Native Tutorials, Java, Kotlin and much more.

We have a SLACK workspace where we share updates related to new job opportunities, articles on Mobile Development/updates from the industry. We also have channels to help you with any questions, dev-help that you require. Just post a question and people would be ready to help you out 🙂

Click on this link to join the AndroidVille SLACK workspace. It’s absolutely free!

If you like any article, do give it a share on Facebook, Linkedin. You can follow me on LinkedIn, Twitter, Quora, and Medium where I answer questions related to Mobile Development, especially Android and Flutter.

If you want to stay updated with all the latest articles, subscribe to the weekly newsletter by entering your email address in the form on the top right section of this page.