How to Clear 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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.