BackHandler is a React Native API used to handle hardware back button presses on Android devices. It allows developers to override default behavior, exit apps, or implement custom navigation logic.
The BackHandler API provides event listeners that trigger when the back button is pressed. Returning true stops default behavior, while false allows it.
// Import BackHandler and useEffect from React Native
import { BackHandler } from "react-native";
import { useEffect } from "react";
useEffect(() => {
const backAction = () => {
return true;
};
const handler = BackHandler.addEventListener(
"hardwareBackPress",
backAction
);
return () => handler.remove();
}, []);
When the hardware back button is pressed, the app will not exit. The event listener intercepts the action and blocks default behavior.
Since we cannot press a physical hardware button in a browser, use the Simulator below.
1. Navigate to "Settings" screen.
2. Press the Triangle (Back) button at the bottom of the phone.
3. Observe how the app intercepts the exit action on the Home screen.
Press the Back button below to try to exit.
// Show alert before exiting the app
import { Alert, BackHandler } from "react-native";
const backAction = () => {
Alert.alert("Exit App", "Do you want to exit?", [
{ text: "Cancel", style: "cancel" },
{ text: "Yes", onPress: () => BackHandler.exitApp() }
]);
return true;
};