
Create apps with React setInterval mastery
Can I use setInterval in React?
How to stop setInterval in ReactJS?
What is the difference between timeout and interval in React?
Why is my setInterval not working in React?
Learn how to use React setInterval for timers, counters, and repeated actions in React applications. This guide covers hooks, cleanup, class components, common issues, and best practices to avoid memory leaks and ensure smooth component behavior.
Working with timers is a common need in frontend applications. In React, the setInterval The function allows developers to execute a task repeatedly after a given delay in milliseconds. While it looks simple at first, using it inside a React component requires proper handling of hooks, cleanup, and re-render behavior to avoid issues like memory leaks or undefined states.
This blog covers how to use React setInterval correctly, practical examples, how to stop it with a stop button, and the right way to handle cleanup functions when the component unmounts.
The setInterval function in JavaScript executes a callback function at fixed time intervals until canceled. In React, it is widely used for counters, updating data at intervals, and repeating tasks inside components.
The method takes two arguments:
When using setInterval in a React project, developers should also handle clearing it using clearInterval(intervalId) to prevent unnecessary timers from continuing after the component unmounts.
The difference lies in how the methods work:
For example, if you want to call a function after 2 seconds, setTimeout is more suitable. But for creating a counter that updates every second, setInterval works better.
| Feature | setTimeout | setInterval |
|---|---|---|
| Execution | Runs the callback function only once after the specified delay. | Repeats the callback function at regular intervals until canceled. |
| Use Case | Suitable when you want to perform an action once after some time (e.g., call a function after 2 seconds). | Suitable for repeated tasks like counters, updating data, or animations. |
| Syntax | ||
| Cancel Method | Canceled using . | Canceled using . |
| React Usage | Often combined with to trigger a function once after rendering. | Used inside or lifecycle methods for repeated rendering actions. |
| Example Scenario | Displaying a message after 2 seconds. | Increasing a counter every second until the user stops it. |
When creating a React component that needs timers, plays a big role. The hook allows you to define side effects, such as starting an interval, while the cleanup function handles clearing the interval when the component unmounts.
Here’s a simple example of a counter using .
This prevents memory leaks that occur if timers keep running after the component is gone.
Sometimes, you may want to cancel the timer created by . The easiest way is to store the and provide a stop button for the user.
In this React component, the user can trigger the interval with a start button and stop it with a stop button.
Even though modern React recommends hooks, class-based components still exist in many apps. The approach here uses lifecycle methods like and .
Here, the class App defines an interval when mounted, and the cleanup happens when the component unmounts.
Looking for a faster way to prototype React projects? Try Rocket.new — it lets you scaffold full-stack applications in minutes, so you can focus more on writing features like timers and less on boilerplate. Give Rocket.new a spin today and simplify your React workflow.
While working with in a React project, developers often face problems:
Always define the interval carefully and clear it when the component unmounts.
If you want to see how other developers faced and discussed the same challenge, you can refer to the GitHub thread here . This discussion will give you practical insights and possible workarounds shared by the React Native community.
Using React setInterval helps create counters, periodic updates, and repeated actions in React applications. By combining , a proper cleanup function, and storing the , you can avoid issues like memory leaks and undefined behavior. Always remember to stop timers when the component unmounts or when the user requests cancellation through a stop button.
setTimeout(callback, delay)setInterval(callback, delay)clearTimeout(timeoutId)clearInterval(intervalId)useEffectuseEffectuseState useEffect from ReactuseEffectsetIntervalconst intervaluseEffectcleanup functioncountsetIntervalinterval idcomponentDidMountcomponentWillUnmountsetIntervaluseEffect hookclearInterval intervalconst intervalconst interval setIntervalinterval idsetInterval functionconsole.logusestate useeffect from reactinterval idimport React, { useState, useEffect } from "react";
function CounterApp() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, 1000);
// useEffect cleanup function to stop interval
return () => clearInterval(interval);
}, []);
return (
<div>
<h2>Counter: {count}</h2>
</div>
);
}
export default CounterApp;
import React, { useState, useEffect } from "react";
function TimerApp() {
const [count, setCount] = useState(0);
const [intervalId, setIntervalId] = useState(null);
const startTimer = () => {
const id = setInterval(() => {
setCount(c => c + 1);
}, 1000);
setIntervalId(id);
};
const stopTimer = () => {
clearInterval(intervalId);
setIntervalId(null);
};
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
</div>
);
}
export default TimerApp;
import React, { Component } from "react";
class App extends Component {
state = { count: 0 };
componentDidMount() {
this.interval = setInterval(() => {
this.setState({ count: this.state.count + 1 });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
<h2>Counter: {this.state.count}</h2>
</div>
);
}
}
export default App;