The setInterval() method executes a function repeatedly at a specified interval. In a React component, we can use the setInterval method to update the component’s state or perform other actions. 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.
Let us understand how to use the setInterval method inside a react component using the following example:
Approach: We will create a counter whose value updates after an interval of a second using the setInterval method.
Implementation and Setup for Creating 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
After the counter-gfg app is created, switch to the new folder counter-gfg by typing the command below:
cd counter-gfg
Step 2: Modify Your project structure:
We will modify the folder and keep the files we need for this example. Now, make sure your file structure looks like this:
Project Structure:
Step 3: Include the following code in your index.html file, located in the public folder of your project directory.
- index.html:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "utf-8" /> < meta name = "viewport" content = "width=device-width, initial-scale=1" /> < meta name = "theme-color" content = "#000000" /> < meta name = "description" content = "Web site created using create-react-app" /> < title >Using setOnterval method in React Components</ title > </ head > < body > < div id = "root" ></ div > </ body > </ html > |
Step 4: Creating the Counter component:
- 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 useState hook initializes the count state variable with a value of 0. Then the useState hook is called with a function as an argument that sets up the interval and stores the returned interval ID as the interval.
- 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 also 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.
App.js:
Javascript
import React, { useState, useEffect } from 'react' ; const Counter = () => { 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 <h1>{count}</h1>; } export default Counter; |
Step 5: Add the following code in the index.js file. The index.js file serves as the main entry point, and inside it, the App.js file is rendered at the root ID of the DOM.
index.js:
Javascript
import React from 'react' ; import ReactDOM from 'react-dom/client' ; import './index.css' ; import App from './App' ; const root = ReactDOM.createRoot(document.getElementById( 'root' )); root.render( <React.StrictMode> <App /> </React.StrictMode> ); |
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 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.