Event Handling
usePageLeave
About
React hook to detect when user is about to leave the page using beforeunload, visibilitychange, and pagehide events. Useful for saving drafts, confirming navigation, or tracking engagement.
Installation
Usage
Parameters
| Parameter | Type | Description |
|---|---|---|
| onPageLeave | () => void | string | Callback executed when user is leaving the page |
Callback Return Value
The callback can return:
void- Just execute side effects (save data, etc.)string- Show a confirmation dialog with the returned message
Examples
Confirm Before Leaving
Track Session Duration
Auto-save on Page Leave
Clear Sensitive Data
Events Handled
The hook listens to three different events for comprehensive coverage:
- beforeunload - Fired when window is about to unload (closing tab, navigating away)
- visibilitychange - Fired when page becomes hidden (tab switch, minimize)
- pagehide - Fired when navigating away (more reliable than beforeunload in some cases)
Features
- Multiple event sources - Covers all common page leave scenarios
- Confirmation dialogs - Return a string to show confirmation
- Auto-save support - Perfect for draft saving functionality
- Analytics tracking - Track session duration and engagement
- Fresh callback - Always uses the latest callback reference
- TypeScript support - Full type definitions included
Browser Support
- beforeunload: All modern browsers
- visibilitychange: Chrome 13+, Firefox 10+, Safari 7+, Edge 12+
- pagehide: Chrome 3+, Firefox 1.5+, Safari 4+, Edge 79+
Notes
- Modern browsers may ignore custom beforeunload messages for security
- The callback is called only once per page leave to avoid duplicates
- Use refs for values you need in the callback to avoid stale closures
- Don't perform long-running operations in the callback
- Network requests in page leave handlers may not complete - use
navigator.sendBeacon()for analytics - The hook uses
useFreshCallbackto ensure the latest callback is always used - Showing confirmation dialogs requires returning a string from the callback