← Back to Chapters

BackHandler in React Native

? BackHandler in React Native

? Quick Overview

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.

? Key Concepts

  • Works only on Android devices
  • Listens to hardware back button presses
  • Can prevent default app exit behavior
  • Commonly used with navigation stacks

? Syntax / Theory

The BackHandler API provides event listeners that trigger when the back button is pressed. Returning true stops default behavior, while false allows it.

? View Code Example
// 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();
}, []);

?️ Live Output / Explanation

When the hardware back button is pressed, the app will not exit. The event listener intercepts the action and blocks default behavior.

? Interactive Example

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.

? 100% 12:00
My App

Home Screen

Press the Back button below to try to exit.

Exit App
Do you want to exit?
CANCEL
YES
System: App running...
? View Code Example
// 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;
};

? Use Cases

  • Prevent accidental app exits
  • Custom navigation control
  • Exit confirmation dialogs
  • Form unsaved data protection

? Tips & Best Practices

  • Always remove event listeners on unmount
  • Use with navigation libraries carefully
  • Avoid blocking back button unnecessarily

? Try It Yourself

  • Create an exit confirmation popup
  • Navigate back to a previous screen manually
  • Disable back button on a login screen