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.
To override the default back press we’ll use BackHandler.addEventListener
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.
What we do here is really simple:
- When the user presses the back button.
- Check the current value. If it’s less than 1,
- Show a toast message asking the user to press it again. Increment the count.
- 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.
- 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:
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:
Would love to hear more suggestions on this and any improvements that can be done. Please mention it in the comments section below.