ComponentWillUnmount with React Hooks

Since we don’t have any lifecycle methods in React functional components, we will make use of the hook useEffect to achieve the same behavior. You can also check my other blog posts where you can do componentDidMount and componentDidUpdate with hooks. Basically, componentWillUnmount is used to do something just before the component is destroyed. Mostly, we will be adding our clean up code here. Let’s see in action how can we do the same in our functional component.

First, we will be importing useEffect hook from the react library.

import { useEffect } from 'react';

Then, we can define a sample functional component.

const App = () => {
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
}

Now, we can add our useEffect hook inside the sample component.

useEffect(() => {
 console.log("Here, useEffect act as componentDidMount")
 return () => {
      console.log("Here, you can add clean up code - componentWillUnmount")
    };
}, [])

Here, useEffect hook returns a function in which we can add our codes to be executed just before destroying our component.

Similar Posts