setInterval in a React component using Hooks.

The Window object in JavaScript allows us to execute code at specified intervals. It provides us with two keys methods   — setTimeout and setInterval. In this article we are going to learn about the setInterval method. Using setInterval inside React components allows us to execute a function or some code at specific intervals. Let’s explore how to use setInterval in React.

The TL;DR:

useEffect(() => { const interval = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(interval); }, []);

The code above schedules a new interval to run every second inside of the useEffect Hook. This will schedule once the React component mounts for the first time. To properly clear the interval, we return clearInterval from the useEffect Hook, passing in the interval.

What is setInterval?

setInterval is a method that calls a function or runs some code after specific intervals of time, as specified through the second parameter.

For example, the code below schedules an interval to print the phrase: “Interval triggered” every second to the console until it is cleared.

setInterval(() => { console.log('Interval triggered'); }, 1000);

setTimeout is a similar method that runs a function once after a delay of time. Learn about setTimeout in React Components using Hooks.

Clearing setInterval in React

A function or block of code that is bound to an interval executes until it is stopped. To stop an interval, you can use the clearInterval() method.

For example, the code below schedules a new interval when the React component mounts for the first time. After the React component unmounts the interval is cleared:

... useEffect(() => { const interval = setInterval(() => { setSeconds(seconds => seconds + 1); }, 1000); return () => clearInterval(interval); }, []); ...

Take a look at the useEffect Hook. At the end of the Hook, we’re returning a new function. This is the equivalent of the componentWillUnmount lifecycle method in a class-based React component. To learn more about the differences between functional components and class-based components check out this guide

The useEffect function returns the clearInterval method with the scheduled interval passed into it. As a result, the interval is correctly cleared and no longer triggers every second after the component unmounts from the DOM.

Above all, when using setInterval, it is imperative that you clear the scheduled interval once the component unmounts.

Using setInterval in React Components

To schedule a new interval, we call the setInterval method inside of a React component, like so:

import React, { useState, useEffect } from 'react'; const IntervalExample = () => { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => { setSeconds(seconds => seconds + 1); }, 1000); return () => clearInterval(interval); }, []); return ( <div className="App"> <header className="App-header"> {seconds} seconds have elapsed since mounting. </header> </div> ); }; export default IntervalExample;

The example above shows a React component, IntervalExample, scheduling a new interval once it mounts to the DOM.

The interval increments the seconds state value by one, every second.

Finally, we display the number of seconds in the return function to show how many seconds have elapsed since the component mounts.

The code above will give us a working demo that looks something like this:

Avatar photo
👋 Hey, I'm James Dietrich
I work full-time at an AI-based startup out of San Francisco, CA. My true passion is to help others. My tutorials help 150,000+ developers learn React and JavaScript every month. Follow on Twitter, or Github.

💬 Leave a comment

Your email address will not be published.

We will never share your email with anyone else.


Thanks for an article!
I have a question. What if I want to run setInterval 10x and then stop. Without removing the component. So, componentWillUnmount() won’t be called out. Is there a way to call clearInterval() after x amount of times?

HI, Great explanation. I have two questions
A) why do you put setSeconds(seconds => seconds + 1); instead setSeconds(seconds + 1); more simply
B) is it correct understand if I remove this return () => clearInterval(interval); from code that React is creating each loop a new setInterval? because he I did it was creating a new count faster and faster. So I understand that React needs to kill the old process to create a new one, but I think Im wrong because setInterval a set Timeout would be the same to put it.

Hi James, Thanks for the post. I have similar code to display time to User. I couldn’t however cover this line under code coverage “setSeconds(seconds => seconds + 1);”. Any idea would be of great help.

Thanks for the article. However I have a question. This solution basically relies on creating a new interval everytime the component re-render due to state change. So process is, start interval, re-render, start interval. If I am creating a clock, the delay will be my delay + re-render delay, because state changes are async process. Is there anyway to get more accurate delay control?

Thanks for putting a tl;dr at the top! I read the article anyway, but it’s nice to know before potentially wasting my time that I’m in the right place!