Clue Mediator

How to use componentWillUnmount() in React Hooks

๐Ÿ“…April 4, 2022
๐Ÿ—ReactJS

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 React Hooks Beginner">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.

Checkout more articles on ReactJS

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.

componentDidMount() {
  window.addEventListener('mousemove', () => { })
}

componentWillUnmount() {
  window.removeEventListener('mousemove', () => { })
}

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

useEffect(() => {
  window.addEventListener('mousemove', () => {});

  // On component unmount, the returned function will be invoked.
  return () => {
    window.removeEventListener('mousemove', () => {})
  }
}, [])

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

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐Ÿ™‚