useBeforeUnload
Prompts the user with a confirmation dialog before leaving or reloading the page.
Loading preview...
The useBeforeUnload hook attaches a beforeunload listener to window to warn users about unsaved changes before they close the tab, reload, or navigate away.
Installation
Usage
Examples
Unsaved Form Changes
Pass a boolean flag so the browser only prompts the user when the form has unsaved edits.
Predicate Function
Pass a predicate function as the first argument to evaluate the condition lazily when the beforeunload event fires.
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
enabled | boolean | (() => boolean) | true | Whether the confirmation prompt is active, or a predicate evaluated when beforeunload fires. |
message | string | undefined | Optional legacy message assigned to event.returnValue. |