componentWillUnmount with react hooks

How to use ComponentWillUnmount with React Hooks

Reading Time: 3 minutes

Hello everyone, today we will see how can we use componentWillUnmount with react hooks. So as you all know that with React Hooks we don’t have lifecycle methods that are present in React Class Component, on the other hand, we have pre-built hooks provided by React some of them are useState, useEffect, useRef, useContext etc. Today we will now look into how can we use useEffect to work as componentWillUnmount.

Why use componentWillUnmount?

First we will discuss why we need componentWillUnmount lifecycle method in react app development. As per official documentation of ReactJScomponentWillUnmount()ย is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created inย componentDidMount().” Read Official Documentation for Lifecycle Methods

So basically we do all the cleanup tasks inside and canceling of all the subscriptions when a component is mounted or updated. Let’s take an example you have added an event listener in your component for any task and that should be removed before the component is destroyed. In this case we can add event remove handler in componentWillUnmount lifecycle method and get our work done.

How to use componentWillUnmount with react hooks?

For this task, we will useEffect hook provided by React JS and call our subscription for event or API inside useEffect and do the cleanup of that particular task inside useEffect hook itself.

Let’s take an example of we are using an event for handling click outside for our popover element and we have to add an event on component initialization and also have to remove it before the component is destroyed. Below we can see how we have added our event at the time of component initialization.

useEffect(() => {
  document.addEventListener('click', handleClick)
})

But here we have one problem, which is the event we added at the component initialization it will be called again and again the time component gets updated. So for this we will add dependencies to useEffect, but here in our case we have to just add this event handler at the time of component initialization and not to be called when the component is updated. So we will pass a blank array of dependencies to useEffect hook to make sure It runs only once at the time of component initialization. Let’s look below code for addition of dependency

useEffect(() => { 
  document.addEventListener('click', handleClick) 
}, [])

Now we are sure that our event will be added only once at the time of component initialization. This is compliance with the react hooks concept. Now we have to do the cleanup at the time our component is getting destroyed.

For this, you might think we will require another function as react class component has componentDidMount and componentWillUnmount, but as per react hooks rule here we have another approach to do the cleanup. We do the initialization and cleanup in the same effect with react hooks. We do it like below.

useEffect(() => { 
   document.addEventListener('click', handleClick);

   return function cleanup () {
     document.removeEventListener('click', handleClick);
   }
}, [])

Here we return a cleanup function with the removing logic of our event. As per react hooks rule whenever an effect received a return function it runs only at the time of cleanup of the component. Also you know that effect runs everytime component renders if you pass a dependency to useEffect in that case the cleanup will run and react will cleans up the function before rendering it next time.

As per official documentation Why did we return a function from our effect?ย This is the optional cleanup mechanism for effects. Every effect may return a function that cleans up after it. This lets us keep the logic for adding and removing subscriptions close to each other. Theyโ€™re part of the same effect!”

I hope you like the post. Please visit my other post which deals with creating a reusable component with React JS for your current application.

8 thoughts on “How to use ComponentWillUnmount with React Hooks”

Leave a Reply

Your email address will not be published. Required fields are marked *