Docs
useUnload

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…
  • To warn about unsaved data before the user closes the tab.
  • To flush telemetry/analytics on beforeunload.
  • For in-SPA navigations — use your router's guard (e.g. React Router's <Prompt />).
  • For async logic that must finish before leaving — beforeunload does not await promises.

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.js router.events, react-router v6+ useBlocker, etc.). useUnload covers only the browser's native beforeunload cycle.

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.returnValue is set to.

See also

  • Full API: useUnload (reference generated from TSDoc).