Open In App

How to use setInterval() method inside React components ?

Last Updated : 21 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
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 :

//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: 

  • Memory Leaks: If the component unmounts before the interval is stopped, the callback function will continue to execute and cause a memory leak. To avoid this, it is important to clear the interval when the component unmounts by calling clearInterval in a cleanup function provided by useEffect.
  • Timing issues: If a component re-renders frequently, the interval may not fire at the expected interval, due to the delay between the time the interval was set and the time the component re-renders.
  • Performance:  When multiple components use the setInterval method, it can lead to performance issues

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

  • The setInterval method is used inside the useEffect hook to increment the count state variable every second (1000 milliseconds).
  • The clearInterval method is used inside the useEffect cleanup function to stop the interval when the component unmounts.
  • The setInterval function takes two arguments: a callback function to be executed repeatedly and a delay in milliseconds. Here, the callback function increments the count state variable by calling the setCount function, which updates the value of the count. 
  • The useEffect hook returns a cleanup function that stops the interval by calling the clearInterval function when the component unmounts or during the count state variable changes. This prevents memory leaks and other issues that arise when using setInterval in a React component.

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.

Javascript




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

Peek-2023-11-20-16-13



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads