Open In App

How to use setInterval() method inside React components ?

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 :



//Implementing the setInterval method
const interval = setInterval(() => {
setState(state + 1);
}, 1000);

However, there are a few caveats to be aware of when using the setInterval method in a React component: 

Therefore, in React, it’s necessary to keep track of the lifecycle of the React components and stop the intervals when the component unmounts. 



Approach:

To show the use of the setInterval method we will create a simple counter-application, where

Steps to Create 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

Example: This example demonstrates a simple counter applicaiton using the setInterval method.




// Filename - App.js
 
import React, { useState, useEffect } from "react";
 
const App = () => {
    const [count, setCount] = useState(0);
 
    useEffect(() => {
        //Implementing the setInterval method
        const interval = setInterval(() => {
            setCount(count + 1);
        }, 1000);
 
        //Clearing the interval
        return () => clearInterval(interval);
    }, [count]);
 
    return (
        <div
            style={{
                display: "flexbox",
                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;

Step to run the application: Run the application by using the following command:

npm start

Output: By default, the React project will run on port 3000. You can access it at http://localhost:3000 on your browser. The value of the count is displayed on the screen and will be incremented every second by the setInterval function.


Article Tags :