useBeforeUnload
Sets up a callback to be fired on the window’s beforeunload event. This is useful for saving data to localStorage or showing a confirmation dialog before the user leaves the page.
Parameters
The callback function to execute when the
beforeunload event fires. The function receives a BeforeUnloadEvent object.To show the browser’s confirmation dialog, set event.returnValue to a string:If
true, the event will be captured during the capture phase instead of the bubbling phase.Type Declaration
Usage Examples
Save Form Data Before Unload
Warn About Unsaved Changes
Analytics Before Page Unload
Persist User Session Data
Common Patterns
Conditional Warning
Combining with useBlocker
Auto-save Before Unload
Important Notes
Browser Behavior
- Custom messages are not supported: Modern browsers ignore custom messages and show their own default warning dialog
- Not all browsers support it consistently: Some browsers may not fire the event in certain conditions
- Mobile browsers: May not support
beforeunloadevents reliably
Best Practices
-
Use
useCallback: Wrap your callback inuseCallbackto avoid adding/removing event listeners on every render -
Use
navigator.sendBeacon: For sending data, usesendBeaconinstead offetchfor better reliability - Don’t rely on it for critical operations: The event may not always fire (crashes, force quit, etc.)
- Keep callbacks lightweight: The browser may kill slow operations
Event Limitations
Related
useBlocker- Block in-app navigationusePrompt- Show confirmation dialog for in-app navigation (deprecated)- Form Guide - Working with forms in React Router
- MDN: beforeunload event