Skip to content

useUnmount

Just like useEffect but runs only when the component unmounts.

Installation

npx rabbithook@latest add use-unmount

Usage

App.tsx
import useUnmount from "@/hooks/use-unmount";
function Component() {
useUnmount(() => {
console.log("Component unmounted");
})
return ();
}

Code

use-unmount.ts
import { useEffect, useRef } from "react";
function useUnMount(cb: () => void) {
const mountedRef = useRef(true);
useEffect(() => {
return () => {
if (mountedRef.current) {
mountedRef.current = false;
cb();
}
};
}, [cb]);
}
export default useUnMount;