useBackEvent
Deprecated
useBackEvent is deprecated and will be removed in a future release. Use useBackHandler instead.
Handlers registered through useBackHandler receive a BackEvent object and can conditionally consume the back action by returning true. To keep the behavior of useBackEvent — always blocking default back navigation while registered — return true from the handler.
// Before
const backEvent = useBackEvent();
useEffect(() => {
const listener = () => {
// handle back action
};
backEvent.addEventListener(listener);
return () => {
backEvent.removeEventListener(listener);
};
}, [backEvent]);
// After
const backHandler = useBackHandler();
useEffect(() => {
const subscription = backHandler.addEventListener(() => {
// handle back action
return true; // block default back navigation
});
return () => {
subscription.remove();
};
}, [backHandler]);A Hook that returns a controller object for registering and removing back events. Using this Hook, you can handle back events only when a specific component is active. Use addEventListener to register back events and removeEventListener to remove them. Registered back events are only active when the user is viewing the screen. The condition for viewing the screen is determined using useVisibility.
Using this Hook, you can define logic to handle back events in specific components.
Signature
function useBackEvent(): BackEventControls;Return Value
- BackEventControls
An object that can control back events. This object includes the
addEventListenermethod for registering events and theremoveEventListenermethod for removing them.
Error
- Error
Throws an error if this hook is not used within a
BackEventProvider.
Example
Example of Registering and Removing Back Events
- When the "Add BackEvent" button is pressed, a back event is registered. After that, pressing the back button shows an alert with "back" and prevents actual navigation.
- When the "Remove BackEvent" button is pressed, the registered event is removed. After that, pressing the back button navigates back normally as per default behavior.
import { useEffect, useState } from 'react';
import { Alert, Button, View } from 'react-native';
import { useBackEvent } from '@granite-js/react-native';
export function UseBackEventExample() {
const backEvent = useBackEvent();
const [handler, setHandler] = useState<{ callback: () => void } | undefined>(undefined);
useEffect(() => {
const callback = handler?.callback;
if (callback != null) {
backEvent.addEventListener(callback);
return () => {
backEvent.removeEventListener(callback);
};
}
return;
}, [backEvent, handler]);
return (
<View>
<Button
title="Add BackEvent"
onPress={() => {
setHandler({ callback: () => Alert.alert('back') });
}}
/>
<Button
title="Remove BackEvent"
onPress={() => {
setHandler(undefined);
}}
/>
</View>
);
}