Clear a timeout or an interval in React with hooks

avatar

Borislav Hadzhiev

Last updated: May 3, 2022

banner

Photo from Unsplash

Clear a timeout or an interval in React with hooks #

To clear a timeout or an interval in React with hooks:

  1. Use the useEffect hook to set up the timeout or interval.
  2. Return a function from the useEffect hook.
  3. Use the clearTimeout() or clearInterval() methods to remove the timeout when the component unmounts.
App.js
import {useEffect, useState} from 'react'; export default function App() { const [isShown, setIsShown] = useState(false); useEffect(() => { const timeoutID = setTimeout(() => { setIsShown(true); }, 1000); return () => { // 👇️ clear timeout when component unmounts clearTimeout(timeoutID); }; }, []); return ( <div> {isShown ? ( <div> <h2>isShown = true</h2> </div> ) : ( <div> <h2>isShown = false</h2> </div> )} </div> ); }

react cleartimeout

If you need to clear an interval, scroll down to the next section.

We passed an empty dependencies array to the useEffect hook because we only want to register the timeout once - when the component mounts.

Note that you can call the useEffect hook multiple times in the same component.

We used the setTimeout() method in our useEffect hook but we have to make sure to clear the timeout to avoid memory leaks.

For example, if the component unmounts before the timer expires and we don't clear the timeout, we would have a memory leak.

The function we returned from the useEffect hook is called when the component unmounts.
App.js
useEffect(() => { const timer = setTimeout(() => { setIsShown(true); }, 1000); // 👇️ runs when component unmounts return () => { clearTimeout(timer); }; }, []);

We used the clearTimeout method to cancel the timeout we previously registered.

If the component unmounts before the delay has expired, the clearTimeout method runs and cancels the timeout.

The approach is the same when using the clearInterval method to cancel an interval that we registered using setInterval.

App.js
import {useEffect, useState} from 'react'; export default function App() { const [count, setCount] = useState(0); useEffect(() => { const intervalID = setInterval(() => { setCount(prev => prev + 1); }, 1000); // 👇️ cancel interval when component unmounts return () => { clearInterval(intervalID); }; }, []); return ( <div> <h2>Count: {count}</h2> </div> ); }

react clearinterval

We run the clearInterval method to cancel the interval we previously registered when the component unmounts.

The cleanup step is important, because we want to make sure we don't have any memory leaks in our application.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.