Open In App

How To Use setInterval() Method Inside React Components?

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Directory

Now 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

Peek-2023-11-20-16-13

  • 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.


Next Article

Similar Reads