How to use componentWillUnmount() in React Hooks

Today we’ll look at how componentWillUnmount can be used with react hooks. As you may know, we don’t have lifecycle methods in React Hooks, but we do have pre-built hooks supplied by React such as useState, useEffect, useRef, and useContext. We’ll look at how we can use useEffect to work as componentWillUnmount today.

The componentWillUnmount is used for cleanup (like removing event listeners, canceling the timer etc). Assume you’re adding an event listener in componentDidMount and removing it in componentWillUnmount as below.

Now the following React Hooks code is the equivalent of the above code.

Know more about the useEffect: How to use useEffect React Hook

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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