# 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

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

## Usage

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

## 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

```ts
function useBeforeUnload(when?: boolean): void
```

| Parameter | Description |
| --- | --- |
| `when` | Ask for confirmation while `true`. Default `true`. |

## Browser support

Not available in Safari iOS.

- Safari on iOS doesn't fire `beforeunload`, so there is no warning there; save drafts as the user types instead.

---

105 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useBeforeUnload.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useBeforeUnload/
Previous: [useScrollLock](https://vincentri.github.io/react-tils/hooks/useScrollLock.md)
Next: [useControllableState](https://vincentri.github.io/react-tils/hooks/useControllableState.md)
