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.
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.
1 2 3 4 5 6 7 | componentDidMount() { window.addEventListener('mousemove', () => { }) } componentWillUnmount() { window.removeEventListener('mousemove', () => { }) } |
Now the following React Hooks code is the equivalent of the above code.
1 2 3 4 5 6 7 8 | 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..!! 🙂