DEV Community

Ghazi Khan
Ghazi Khan

Posted on

Use componentWillUnmount with React Hooks

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 componentWillMount?

First we will discuss why we need componentWillUnmount lifecycle method in react app development. As per official documentation of ReactJS "componentWillUnmount() 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.

Read full Article Here

Top comments (2)

omniteq profile image
omniteq • Edited

Thank Ghazi! You inspired me.
I don't know what might go wrong, but I perform a localStorage update in the useEffect cleanup function and, as for now, it works flawlessly!

When I reload a page (electron), react doesn't call the cleanup function.

yahyaahmed01 profile image
Yahya Ahmed

Nicely explained. But how to clear all states when unmounting?
doesnt work this way