BackHandler is Android-only. On iOS, it has no effect.
The BackHandler API detects hardware back button presses on Android devices, allowing you to control back button behavior. Event subscriptions are called in reverse order (last registered first), and if one subscription returns true, earlier subscriptions won’t be called.
Import
import { BackHandler } from 'react-native';
Methods
addEventListener()
static addEventListener(
eventName: 'hardwareBackPress',
handler: () => boolean | null | undefined
): { remove: () => void }
Adds an event listener for hardware back button presses.
Parameters:
eventName: Must be 'hardwareBackPress'
handler: Function that returns true if it has handled the back press, false or null/undefined otherwise
Returns: An object with a remove() method to unsubscribe the listener.
Example
import React, { useEffect } from 'react';
import { BackHandler } from 'react-native';
function MyComponent() {
useEffect(() => {
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
() => {
// Handle back button press
// Return true to prevent default behavior (exit app)
// Return false to let default behavior happen
if (shouldPreventBack) {
// Do something
return true;
}
return false;
}
);
return () => backHandler.remove();
}, []);
return null;
}
exitApp()
Programmatically invokes the default back button functionality to exit the app.
Example
import { BackHandler } from 'react-native';
BackHandler.exitApp();
Usage Example
import React, { useEffect } from 'react';
import { BackHandler, Alert } from 'react-native';
function App() {
useEffect(() => {
const backAction = () => {
Alert.alert('Hold on!', 'Are you sure you want to exit?', [
{
text: 'Cancel',
onPress: () => null,
style: 'cancel',
},
{ text: 'YES', onPress: () => BackHandler.exitApp() },
]);
return true;
};
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
backAction
);
return () => backHandler.remove();
}, []);
return (
// Your app content
);
}
Notes
- BackHandler only works on Android. On iOS, it’s a no-op.
- Event handlers are called in reverse order (LIFO - Last In, First Out).
- If a handler returns
true, earlier handlers won’t be called.
- If no handlers return
true, exitApp() is automatically called.