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
- React Interview Questions and Answers
- Sticky element on a scroll in React
- How to validate react-select dropdown in React
- Checkbox list example in React
- Create a toggle switch in React
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..!! ๐