Effects
useUnmount
Runs a cleanup function once, when the component unmounts.
Demo
live · imported from hookli
mounted — cleanup armed
- status
- mounted
- cleanups run
- 0
import { useUnmount } from "hookli";
export function Demo() {
useUnmount(() => {
console.log("cleanup on unmount");
});
return <p>Watch the console when I unmount.</p>;
}Usage
import { useUnmount } from "hookli";
export function Demo() {
useUnmount(() => {
console.log("cleanup on unmount");
});
return <p>Watch the console when I unmount.</p>;
}API
useUnmount(fn: () => void): voidParameters
| Name | Type | Default | Description |
|---|---|---|---|
| fn | () => void | — | Called exactly once when the component unmounts. The latest closure is captured in a ref, so it always sees fresh values. |
Returns
This hook returns nothing.
Hook
The implementation, straight from hookli. Copy it, or install the package.
import { useEffect, useRef } from "react";
export const useUnmount = (fn: () => void) => {
const fnRef = useRef(fn);
// The latest closure every render, but only invoked on unmount.
fnRef.current = fn;
useEffect(() => () => fnRef.current(), []);
};