useWillUnmount
Runs the initial callback as an effect cleanup when a component unmounts.
About
useWillUnmount registers cleanup-only work such as releasing an imperative resource or recording that a component has left the tree.
Examples
import { useState } from "react";
import { useWillUnmount } from "rooks";
function Session({ onClose }: { onClose: () => void }) {
useWillUnmount(onClose);
return <p>Session is open</p>;
}
export default function SessionDemo() {
const [open, setOpen] = useState(true);
const [status, setStatus] = useState("Open");
return (
<section>
{open && <Session onClose={() => setStatus("Closed")} />}
<p role="status">{status}</p>
<button type="button" onClick={() => setOpen(false)}>
Close session
</button>
</section>
);
}Parameters
callback: () => void is required.
Return value
The hook returns void; the callback's return value is ignored.
Behavior and lifecycle
The initial callback is returned from an empty-dependency effect and is not refreshed on later renders. If cleanup needs current values, provide a stable callback that reads a ref. React Strict Mode replays effect cleanup during development, so the callback can run before the final physical unmount and must be safe to repeat.
Compatibility and accessibility
No browser API is required, and cleanup does not run during server rendering because the effect never starts there. Avoid relying on unmount cleanup for guaranteed network delivery or critical persistence; browsers and processes can terminate without running React cleanup.