Documentation

Hooks

useBeforeUnload

Warn people before they close the tab or reload the page with unsaved changes, using the browser's beforeunload prompt.

Preview

Saved

Edit the reply, then reload the tab.

Usage

import { useBeforeUnload } from '@vitnode/core/hooks/use-before-unload'
const [isDirty, setIsDirty] = React.useState(false)

useBeforeUnload(isDirty)

While enabled is true, closing the tab, reloading or typing a new address makes the browser ask "Leave site?". Set it back to false once the changes are saved.

Check at the last moment

Pass a function and the hook calls it only when someone tries to leave. Handy when the dirty state lives in a ref that doesn't re-render:

const hasUnsavedChanges = React.useRef(false)

useBeforeUnload(() => hasUnsavedChanges.current)

Good to know

  • The browser writes the message. Modern browsers ignore custom text. message only matters for old ones.
  • In-app navigation isn't covered. Clicking a router Link doesn't unload the page, so no prompt.
  • Use it sparingly. A prompt on every page teaches people to click "Leave" without reading.

Options

Prop

Type

The hook returns nothing.