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

  • whenboolean

    Warn only while there are unsaved changes.

  • options.backButtonboolean
    Default: false

    Also ask when the browser back button is pressed.

  • options.messagestring
    Default: '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.