usePageLeave
Calls a callback for unload, page-hide, and hidden-document signals.
About
usePageLeave observes three browser signals associated with leaving or hiding a page: beforeunload, pagehide, and a transition of document.visibilityState to "hidden". It does not detect the pointer leaving the viewport.
Example
import { useState } from "react";
import { usePageLeave } from "rooks";
export default function DraftEditor() {
const [draft, setDraft] = useState("");
usePageLeave(() => {
localStorage.setItem("draft", draft);
});
return (
<label>
Draft
<textarea
value={draft}
onChange={(event) => setDraft(event.target.value)}
/>
</label>
);
}Parameters
onPageLeave: a no-argument callback returningvoid | string. The active listeners use the latest callback.
Return value
The hook returns void.
Behavior and lifecycle
On beforeunload, the hook marks the page as leaving and invokes the callback. A returned string causes preventDefault() and assignment to event.returnValue, requesting the browser's generic confirmation dialog. A hidden-document or pagehide signal also invokes the callback unless beforeunload already marked the page as leaving. Hidden-document followed by pagehide can still call the callback twice, so make it safe to repeat. All three listeners are removed on unmount.
Compatibility and accessibility
The hook does nothing during server rendering. Browsers may skip unload events, especially on mobile, and modern browsers control confirmation-dialog text rather than displaying the returned string. Keep callbacks synchronous and small; do not rely on an async request completing. Avoid routine leave prompts because they interrupt navigation and assistive-technology workflows.
Related
- useDocumentVisibilityState exposes visibility as render state.
- SSR and browser APIs covers browser-only effects.