How to use ComponentWillUnmount with React Hooks

Lets learn how to implement ComponentWillUnmount with React Hooks, and do the necessary cleanup in out React application with React Hooks

Frameworks

Front End Development

React JS

How to 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 componentWillUnmount?

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.

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.


Get latest updates

I post blogs and videos on different topics on software
development. Subscribe newsletter to get notified.


You May Also Like

Master Pagination, Search, and Language Filtering in NextJS with Prisma ORM

Master Pagination, Search, and Language Filtering in NextJS with Prisma ORM

Learn how to implement pagination, search, and language filtering in a NextJS app using Prisma ORM. Enhance your code snippet sharing app's functionality with these essential features for improved user experience.

When to Use a Monorepo: Benefits, Drawbacks, and Practical Examples

When to Use a Monorepo: Benefits, Drawbacks, and Practical Examples

Learn when to use a monorepo, its benefits, and drawbacks. This guide includes practical examples to help you decide if a monorepo is right for your development projects.

NodeJS: An Introduction to Streams for Efficient Data Handling

NodeJS: An Introduction to Streams for Efficient Data Handling

Learn the basics of NodeJS streams, including reading, writing, and piping data, to efficiently handle large data sets in your applications with practical code examples.