DEV Community

loading...
Cover image for Exit app when back button is pressed twice in React Native.

Exit app when back button is pressed twice in React Native.

Gautham Vijayan
React.js and React Native developer. Creator of Neo Budget
・2 min read

In this post I will discuss how you can implement "exiting your app when back button is pressed twice".

So if your user is using your app and accidently presses the back button, the app will exit. So to warn the user about exiting the app we can use BackHandler provided by the react native library.

So the flow is when the user touches the back button it will not exit the app and when he double touches it, we will be alerting him to either go back to the app or exit the app.

So below is the code to implement it.


import React, { useEffect } from "react";
import { Text, View,BackHandler, Alert } from "react-native";

const App = () => {
  useEffect(() => {
    const backAction = () => {
      Alert.alert("Hold on!", "Are you sure you want to go back?", [
        {
          text: "Cancel",
          onPress: () => null,
          style: "cancel"
        },
        { text: "YES", onPress: () => BackHandler.exitApp() }
      ]);
      return true;
    };

    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      backAction
    );

    return () => backHandler.remove();
  }, []);

  return (
    <View >
      <Text style>Gautham's Backhandler Example </Text>
    </View>
  );
};


export default App;

Enter fullscreen mode Exit fullscreen mode

Implement it in the App.js where you will be defining navigators.

So here we are adding event listener called "hardwareBackPress" to listen to users' action on back button and call the function in useEffect.

So thats how you can easily implement "exiting your app when back button is pressed twice" functionality in your react native app.

This may not be that much significant for small apps. But if people are using your app to enter data inputs and accidently touched the back button and the app closes, it may provide for bad UX experience.

Best documentation on React BackHandler Functionality I referrerd to :
React Native Doc

Thank you for reading!!

Check out My Budget app on Google play store neo-budget

Check out my portfolio: Gautham's portfolio

Check out my blog: coding-magnified.tech

Check React Project about budgeting: neo-budget

My Other Articles:

Discussion (2)

Collapse
shaileshcodes profile image
Shailesh Vasandani

Cool implementation! It's always good to keep in mind when users accidentally leave a page, especially when they're entering lots of data.

Thanks for sharing!

Collapse
gautham495 profile image
Gautham Vijayan Author

Yeah I forgot to implement this functionality in my app and my friend pointed it out to implement it in the next update. Glad you liked it.