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

Gautham Vijayan - Jan 10 '21 - - Dev Community

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

To know more about React & React Native you can checkout my courses in Udemy.

https://www.udemy.com/course/react-native-for-absolute-beginners-with-react-hooks/

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player