useUnload
Hook that registers a handler for the window's beforeunload event,
allowing you to interrupt (or just react to) the user leaving the page:
external route change, tab close or refresh.
The handler is kept in an internal ref, so changes between renders do not
force the listener to re-register.
When to use
| ✅ Use when… | 🚫 Avoid when… |
|---|---|
|
|
Signature
useUnload(handler: (e: Event) => string | undefined | void);Example
import { Card } from '@apollion-dsi/core/containers/card';
import { Text } from '@apollion-dsi/core/elements/text';
import { Link } from '@apollion-dsi/core/elements/link';
import { useUnload } from '@apollion-dsi/core/hooks';
function Component() {
useUnload((e: Event) => {
e.preventDefault();
e.returnValue = '';
});
return (
<Card width="100%">
<Text text="Closing the tab fires the browser's native beforeunload handler." />
<Link href="/">LINK</Link>
</Card>
);
}Note: intercepting in-SPA navigation (the equivalent of react-router v5's legacy
<Prompt>) is the consumer framework's responsibility (Next.jsrouter.events, react-router v6+useBlocker, etc.).useUnloadcovers only the browser's nativebeforeunloadcycle.
Note: don't over-rely on a custom prompt message — modern browsers ignore any custom string and show their own generic confirmation text regardless of what
e.returnValueis set to.
See also
- Full API:
useUnload(reference generated from TSDoc).