How To Use setInterval() Method Inside React Components?
Last Updated :
10 May, 2025
The setInterval() method executes a function repeatedly at a specified interval. We can use the setInterval method in a React component to update the component's state or perform other actions.
Syntax:
setInterval(callback, delay);
- callback: The function you want to run periodically.
- delay: The time interval (in milliseconds) between each function call.
Note=> In React, it's necessary to keep track of the lifecycle of the React components and stop the intervals when the component unmounts. Using setInterval()
in React can be tricky but is essential for tasks like timers.
How to Use setInterval() Inside React Components?
In React, setInterval() can be used within components to perform tasks like updating state at regular intervals. However, it’s important to handle it properly because React components can re-render and the interval may not work as expected if not cleaned up properly.
- Setting up the interval: We can set up an interval inside the useEffect hook, which ensures that side effects like setting intervals are correctly managed when the component mounts.
- Updating state: Use useState to store values that change over time.
- Cleaning up: Since React components can unmount, it's essential to clear the interval when the component unmounts to prevent memory leaks or unnecessary function calls.
Steps to Create a React Application
Step 1: Make a project directory, head over to the terminal, and create a React app named counter-gfg using the following command:
npx create-react-app counter-gfg
Step 2: After the counter-gfg app is created, switch to the new folder counter-gfg by typing the command below:
cd counter-gfg
Project Structure
Final Project DirectoryNow let's understand this with the help of example:
JavaScript
import React, { useState, useEffect } from "react";
const App = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("useEffect runs");
const interval = setInterval(() => {
setCount((prevCount) => prevCount + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div
style={{
display: "flex",
margin: "auto",
textAlign: "center",
}}
>
<h1 style={{ color: "green" }}>
GeeksforGeeks
</h1>
<h3>
React Example for using setInterval method
</h3>
<h1>{count}</h1>
</div>
);
};
export default App;
Run the application by using the following command
npm start
Output

- The code initializes a count state variable and sets up a useEffect hook that increments count every second using setInterval.
- The effect cleans up by clearing the interval when the component unmounts, preventing memory leaks.
- The count value is displayed in the component, and it updates continuously without any predefined stopping condition.
Best Practices for Using setInterval() in React
- Always Clean Up the Interval: Always clear the interval when the component unmounts. Failing to do so can lead to memory leaks and unexpected behavior.
- Use useEffect for Functional Components: The useEffect hook provides an easy and declarative way to handle side effects, including setting and clearing intervals in functional components.
- Avoid Frequent State Updates: While using setInterval(), avoid setting state too frequently as it might cause performance issues due to excessive re-renders. If you're updating the state every second, make sure it’s necessary for the UI to update at that frequency.
- Use clearInterval(): Always remember to use clearInterval() to stop the interval when it is no longer needed, especially if the component unmounts.
Conclusion
setInterval() in React allows you to perform actions at regular intervals, such as updating state. Using useEffect ensures proper setup and cleanup of intervals, preventing memory leaks. It's important to clear the interval when the component unmounts and avoid excessive state updates to ensure efficient performance in React applications.
Similar Reads
How to update the State of a component in ReactJS ? To display the latest or updated information, and content on the UI after any User interaction or data fetch from the API, we have to update the state of the component. This change in the state makes the UI re-render with the updated content. Prerequisites: NPM & Node.jsReact JSReact StateReact
3 min read
How to use Fade Component in React JS ? The Fade Component, available in Material UI for React, seamlessly adds a fade animation to a child element or component. Integrating this component into a React JS project is straightforward and enhances the user interface with ease.Prerequisites:React JSMaterial UIPopper Transitions: The Transitio
2 min read
ReactJS UNSAFE_componentWillUpdate() Method The componentWillUpdate() method provides us the control to manipulate our React component just before it receives new props or state values. It is called just before the rendering of our component during the updating phase of the React Life-cycle ,i.e., this method gets triggered after the updation
3 min read
How re-render a component without using setState() method in ReactJS ? In React, to re-render a class-based component with an updated state we generally use the setState() method. But instead, we can use other methods to re-render a component without using setState(). Prerequisites:Â NPM & Node.jsReact JSReactJS propsReactJS forceUpdate() methodApproaches to re-rend
3 min read
How to use react-countup module in ReactJS ? While displaying some count count-up animation enhances the appearance with an increasing count value on the web page. To display count up the animation of numbers we need to use the react-countup module in ReactJSPrerequisites:NPM & Node.jsReact JSApproach:Using react-countup module in React JS
2 min read
Using setTimeouts in React Components The setTimeout method in React enables the execution of a function after a specified time interval. This functionality is pivotal in web development for implementing time-based behaviors, offering a spectrum of applications ranging from user interface enhancements to asynchronous operations. The set
6 min read
How to locally manage component's state in ReactJS ? Any component in React JS majorly depends on its props and state to manage data. A component's state is private to it and is responsible for governing its behavior throughout its life. A state is nothing but a structure that records any data changes in a react application. It can be used for storing
2 min read
Implementing State in React Components In React State is an object that holds some information which can be changed overtime. Whenever a State is updated it triggers re-rendering of the component. In React components State can be implemented by default in class components and in functional components we have to implement state using hook
3 min read
What is ComponentWillMount() method in ReactJS ? ReactJS requires several components to represent a unit of logic for specific functionality. The componentWillMount lifecycle method is an ideal choice when it comes to updating business logic, app configuration updates, and API calls. PrerequisitesReact JSReact JS class componentsComponentWillMoun
4 min read
ReactJS UNSAFE_componentWillReceiveProps() Method The componentWillReceiveProps() is invoked before our mounted React component receives new props. It is called during the updating phase of the React Life-cycle. It is used to update the state in response to some changes in our props. We can't call this with initial props during mounting because Rea
3 min read