useLeaveWarning
Warn before the tab is closed or the back button is used with unsaved changes.
useLeaveWarning(when, { backButton = false, message, onBack })While when is true, closing or reloading the tab shows the browser's "Leave site?" prompt. Browsers ignore custom text there and show their own message. Add backButton to ask when the browser back button is pressed too: browsers cannot cancel that button, so the hook keeps one extra history entry while when is true, puts it back each time the reader chooses to stay, and removes it when when turns false. By default the question is a confirm box (message); pass onBack(leave) to ask in your own dialog and call leave() to go back after all.
Links inside your app are not intercepted: use useUnsavedChanges for those. With a router, prefer the router's own blocker over backButton, since both read the same history.
Nothing to lose yet: type something.
API
whenbooleanWarn only while there are unsaved changes.
options.backButtonbooleanDefault:falseAlso ask when the browser back button is pressed.
options.messagestringDefault:'Leave this page? Changes you made may not be saved.'Question in the confirm box.
options.onBack(leave: () => void) => voidAsk in your own dialog; call
leave()to go back.
| Prop | Type | Default | Description |
|---|---|---|---|
when | boolean | – | Warn only while there are unsaved changes. |
options.backButton | boolean | false | Also ask when the browser back button is pressed. |
options.message | string | 'Leave this page? Changes you made may not be saved.' | Question in the confirm box. |
options.onBack | (leave: () => void) => void | – | Ask in your own dialog; call leave() to go back. |