All hooks / Browser APIs

useBeforeUnload

105 B minified and brotliedSourceMarkdown! Not available in Safari iOS

Asks the browser to confirm before the user closes the tab, reloads, or navigates to another site, while when is true.

Browsers show their own generic message; custom text is not possible. The listener is only added while when is true, because an active beforeunload listener can stop the browser from caching the page for instant back/forward.

Import

import { useBeforeUnload } from '@vincent.ri/react-tils'
// or only this hook
import { useBeforeUnload } from '@vincent.ri/react-tils/useBeforeUnload'

Usage

const [draft, setDraft] = useState('')
useBeforeUnload(draft !== savedDraft)

Live demo

Check the box, then try to reload.

When to use it

A form or editor has unsaved changes.

When not to

You need to save data on exit; use pagehide or visibilitychange with navigator.sendBeacon. This does not catch client-side navigation (Next.js <Link>, router pushes); block those in your router.

API

function useBeforeUnload(when?: boolean): void
ParameterDescription
whenAsk for confirmation while true. Default true.

Browser support

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
beforeunload eventLimited availability1+12+1+3+18+✕
  • Safari on iOS doesn't fire beforeunload, so there is no warning there; save drafts as the user types instead.

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).