Categories
JavaScript Answers

How to clear timeouts and intervals with React hooks?

Spread the love

Sometimes, we want to clear timeouts and intervals with React hooks.

In this article, we’ll look at how to clear timeouts and intervals with React hooks.

How to clear timeouts and intervals with React hooks?

To clear timeouts and intervals with React hooks, we call clearTimeout in the callback that we return in the useEffect hook callback.

For instance, we write

const Comp = () => {
  //...
  React.useEffect(() => {
    const timeoutID = window.setTimeout(() => {
      //...
    }, 1000);

    return () => window.clearTimeout(timeoutID);
  }, []);

  //...
};

to call useEffect with a callback that calls setTimout to run its callback with a 1 second delay.

Then we return a function that calls clearTimeout with the timeoutId returned by setInterval to clear the timer when the component unmounts.

Conclusion

To clear timeouts and intervals with React hooks, we call clearTimeout in the callback that we return in the useEffect hook callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *