All hooks / Browser APIs
useBeforeUnload
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| Parameter | Description |
|---|---|
when | Ask for confirmation while true. Default true. |
Browser support
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| beforeunload eventLimited availability | 1+ | 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).