useUnmount is a hook that executes a given function once on component unmount.
- On mount, the hook does nothing.
- On unmount, it invokes the latest version of the callback (via
useLiveRef) so the final version of your function runs.
function useUnmount(callback: UseUnmountCallback): void;-
Parameters
callback— a function to run when the component unmounts.
-
Returns:
void.
import { useEffect } from 'react';
import { useUnmount } from '@webeach/react-hooks/useUnmount';
function onFocus() {
// ...
}
export function Chat() {
useEffect(() => {
window.addEventListener('focus', onFocus);
return () => window.removeEventListener('focus', onFocus);
}, []);
useUnmount(() => {
window.removeEventListener('focus', onFocus);
});
return null;
}import { useEffect } from 'react';
import { useUnmount } from '@webeach/react-hooks/useUnmount';
function tick() {
// ...
}
export function Ticker() {
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);
useUnmount(() => {
// optional fallback cleanup
clearIntervalAllSomehow?.();
});
return null;
}import { useUnmount } from '@webeach/react-hooks/useUnmount';
function saveDraft() {
// ...
}
export function Editor() {
useUnmount(() => {
saveDraft();
console.log('Editor unmounted');
});
return <textarea />;
}-
Unmount trigger
- The callback runs exactly once when the component unmounts.
-
Callback freshness
- Uses
useLiveRef, so the most recentcallbackis invoked even if it changed between renders.
- Uses
-
SSR‑safe
- Side effects are attached only in the browser. Nothing runs on the server.
- Releasing resources: timers, subscriptions, controllers, WebSockets.
- Saving state or sending analytics when leaving a page/section.
- Atomic finalization of operations started by the component.
- If cleanup can be returned from the same
useEffectthat created the resource — prefer doing it in the effect’sreturncleanup. - For logic that should run on every update — use
useEffectwith dependencies.
Exported types
UseUnmountCallback- A callback invoked on component unmount:
() => any.
- A callback invoked on component unmount: