30% offEnding soon
useBeforeUnloadLoading saved progress…

useBeforeUnload

useBeforeUnload conditionally asks the browser to confirm before leaving a page that contains unsaved work. You will manage a beforeunload listener whose lifetime follows a boolean flag. The calling component decides whether work is unsaved; the hook only manages the browser subscription. The browser owns the wording and decides whether a dialog appears.

Signature

function useBeforeUnload(shouldWarn?: boolean): void

Examples

function SavedEditor() {
  useBeforeUnload(false);
  // No beforeunload listener is attached.
  return null;
}
function DirtyEditor({ isDirty }) {
  useBeforeUnload(isDirty);
  return null;
}

// false -> true: attach one listener
// true -> true: keep the existing listener
// true -> false: remove the exact listener that was attached

Notes

  • DefaultshouldWarn defaults to false.
  • Lifecycle — attach one listener only while shouldWarn is true, and remove that exact listener when it becomes false or the component unmounts.
  • Compatibility — call event.preventDefault() and assign event.returnValue = true for legacy support.
  • Server rendering — do nothing when window is unavailable.
  • Independence — multiple hook instances own separate handlers and remove only their own subscriptions.
  • Scope — do not implement custom messages, autosave, router blocking, visibilitychange, pagehide, unload, or forced dialogs.