HooksuseUnmount

useUnmount()

The useUnmount() hook allows you to run a cleanup function right before the component is removed from the DOM. It acts as a semantic alias for the cleanup phase of useEffect(..., []).

Import

typescript
import { useUnmount } from 'the-react-hooks';

Usage

Mount the component, then Unmount it to trigger the callback.

Empty Slot
Activity Log
No activity yet...
Component.tsx
import { useUnmount } from 'the-react-hooks';

const Child = () => {
  useUnmount(() => {
    console.log('Good bye! I am unmounting.');
  });

  return <div>I am alive</div>;
};

export const Component = () => {
  const [show, setShow] = useState(true);

  return (
    <div>
      <button onClick={() => setShow(false)}>
        Unmount Child
      </button>

      {show && <Child />}
    </div>
  );
}

API

Arguments

  • fn () => void The callback function to run on unmount.

Returns

This hook returns void.