Skip to main content

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

(event: BeforeUnloadEvent) => any
required
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:
object
boolean
default:false
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 beforeunload events reliably

Best Practices

  1. Use useCallback: Wrap your callback in useCallback to avoid adding/removing event listeners on every render
  2. Use navigator.sendBeacon: For sending data, use sendBeacon instead of fetch for better reliability
  3. Don’t rely on it for critical operations: The event may not always fire (crashes, force quit, etc.)
  4. Keep callbacks lightweight: The browser may kill slow operations

Event Limitations