usePageLeave
Detects when the user tries to leave the page.
Installation
Props
Prop | Type | Default | Description |
---|---|---|---|
confirmationMessage | string | - | Custom message to show in the browser's confirmation dialog. Note: Most modern browsers ignore custom messages for security reasons. |
showConfirmation | boolean | false | Whether to show the browser's confirmation dialog when the user tries to leave the page. |
Data
Property | Type | Description |
---|---|---|
isPageLeft | boolean | Indicates whether the user has left the page (tab is in background or hidden). |
onPageLeave | (callback: () => void) => void | Function to register a callback that will be executed when the user leaves the page. |
Key Features & Details
- Tab Switch Detection: Uses the
visibilitychange
event to detect when the user switches tabs or minimizes the browser. - Page Close/Reload Detection: Uses the
beforeunload
event to detect when the user tries to close or reload the page. - Confirmation Dialog: Optionally shows a confirmation dialog when the user tries to leave the page.
- Custom Callback: Allows you to execute custom logic when the user leaves the page.
- SSR Safe: Checks for the
window
object before adding event listeners, making it safe to use in SSR/Next.js environments.
Examples
Save Draft on Page Leave
function Editor() {
const { onPageLeave } = usePageLeave({
showConfirmation: true,
confirmationMessage:
'You have unsaved changes. Are you sure you want to leave?',
});
useEffect(() => {
onPageLeave(() => {
// Auto-save draft when user leaves
saveDraft();
});
}, [onPageLeave]);
return <div>Editor content</div>;
}
Track User Engagement
function Analytics() {
const { isPageLeft, onPageLeave } = usePageLeave();
useEffect(() => {
onPageLeave(() => {
// Send analytics when user leaves
trackUserEngagement();
});
}, [onPageLeave]);
return <div>User is {isPageLeft ? 'not' : ''} engaged with the page</div>;
}