Interview frequency: …
Short answer
Use the BackHandler module to add a listener for the "hardwareBackPress" event and return true to prevent default navigation and perform a custom action, such as confirming exit or closing a modal.
Explanation
On Android, users expect familiar behavior when pressing the physical Back button or using the edge-back gesture. If a form has unsaved changes, BackHandler can intercept Back and show a confirmation dialog. Return false if you want to let the system complete its normal back action.
Code example
import { useEffect } from 'react';
import { BackHandler, Alert } from 'react-native';
function EditProfileScreen() {
useEffect(() => {
const onBackPress = () => {
Alert.alert(''Alert', 'Do you want to leave without saving changes?', [
{ text: 'Cancel', style: 'cancel' },
{ text: 'Leave', onPress: () => BackHandler.exitApp() }
]);
return true; // Prevents default immediate back navigation
};
const sub = BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () => sub.remove();
}, []);
}Common mistakes
- Forgetting to call the cleanup function sub.remove(), leaving the Back interception active on every other screen in the app.