From the React doc:

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

So you will need to mimic lifecycle methods from class component in a functional components.

Code inside componentDidMount run once when the component is mounted. useEffect hook equivalent for this behavior is:

useEffect(() => {

// Your code here

}, []);

Notice the second parameter here is empty array [] . This means that it will run only once.

Without the second parameter the useEffect hook will be called on every render of the component which can be dangerous.

useEffect(() => {

// Your code here

});

componentWillUnmount is use for cleanup (like removing event listeners,.. etc). Say you are adding a event listener in componentDidMount and removing it in componentWillUnmount as below.

componentDidMount() {

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

} componentWillUnmount() {

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

}

Hook equivalent of above code will be something like this: