Sign in
Create apps with React setInterval mastery
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 | setTimeout(callback, delay) | setInterval(callback, delay) |
Cancel Method | Canceled using clearTimeout(timeoutId) . | Canceled using clearInterval(intervalId) . |
React Usage | Often combined with useEffect to trigger a function once after rendering. | Used inside useEffect 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, useState useEffect from React
plays a big role. The useEffect
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 setInterval
.
1import React, { useState, useEffect } from "react"; 2 3function CounterApp() { 4 const [count, setCount] = useState(0); 5 6 useEffect(() => { 7 const interval = setInterval(() => { 8 setCount(prevCount => prevCount + 1); 9 }, 1000); 10 11 // useEffect cleanup function to stop interval 12 return () => clearInterval(interval); 13 }, []); 14 15 return ( 16 <div> 17 <h2>Counter: {count}</h2> 18 </div> 19 ); 20} 21 22export default CounterApp; 23
const interval
setInterval inside the useEffect
hook.cleanup function
clears the interval when the component unmounts.count
value updates every second, re-rendering the component on screen.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 setInterval
. The easiest way is to store the interval id
and provide a stop button for the user.
1import React, { useState, useEffect } from "react"; 2 3function TimerApp() { 4 const [count, setCount] = useState(0); 5 const [intervalId, setIntervalId] = useState(null); 6 7 const startTimer = () => { 8 const id = setInterval(() => { 9 setCount(c => c + 1); 10 }, 1000); 11 setIntervalId(id); 12 }; 13 14 const stopTimer = () => { 15 clearInterval(intervalId); 16 setIntervalId(null); 17 }; 18 19 return ( 20 <div> 21 <h2>Counter: {count}</h2> 22 <button onClick={startTimer}>Start</button> 23 <button onClick={stopTimer}>Stop</button> 24 </div> 25 ); 26} 27 28export default TimerApp; 29
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 componentDidMount
and componentWillUnmount
.
1import React, { Component } from "react"; 2 3class App extends Component { 4 state = { count: 0 }; 5 6 componentDidMount() { 7 this.interval = setInterval(() => { 8 this.setState({ count: this.state.count + 1 }); 9 }, 1000); 10 } 11 12 componentWillUnmount() { 13 clearInterval(this.interval); 14 } 15 16 render() { 17 return ( 18 <div> 19 <h2>Counter: {this.state.count}</h2> 20 </div> 21 ); 22 } 23} 24 25export default App; 26
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 setInterval
in a React project, developers often face problems:
useEffect hook
, or if the cleanup function is missing.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.
clearInterval interval
in a useEffect cleanup function.const interval
or const interval setInterval
properly to store the interval id
.setInterval function
is asynchronous, so be aware of how React handles updates.console.log
during development to test when intervals are active.Using React setInterval helps create counters, periodic updates, and repeated actions in React applications. By combining usestate useeffect from react
, a proper cleanup function, and storing the interval id
, 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.