How to Clear setTimeout in React useEffect Hook?

Clearing setTimeout in React useEffect hook

React useEffect hook expects its callback function to either return nothing or a clean-up function. If you return a clean-up function in the useEffect callback, then it is run in the following instances:

  1. Before the component is removed from the UI;
  2. Before executing the next effect (for example when the dependencies of the hook change, and it needs to run again with new values).

Therefore, you can simply clear the setTimeout() timer in this clean-up function, for example in the following way:

// ...

useEffect(() => {
    const timerId = setTimeout(() => {
        // do something
    }, 2000);

    return () => clearTimeout(timerId);
}, []);

// ...

This would help you avoid memory leaks because the clean-up function will clear the timer each time the component re-renders or when it unmounts.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.