React useComponentWillUnmount hook

Angelos Chalaris · React, Hooks, Effect · Oct 13, 2021

Executes a callback immediately before a component is unmounted and destroyed.

  • Use the useEffect() hook with an empty array as the second argument. Return the provided callback to be executed only once before cleanup.
  • Behaves like the componentWillUnmount() lifecycle method of class components.
const useComponentWillUnmount = onUnmountHandler => {
  React.useEffect(
    () => () => {
      onUnmountHandler();
    },
    []
  );
};
const Unmounter = () => {
  useComponentWillUnmount(() => console.log('Component will unmount'));

  return <div>Check the console!</div>;
};

ReactDOM.render(<Unmounter />, document.getElementById('root'));

Would you like to help us improve 30 seconds of code?Take a quick survey

Recommended snippets