How to update a component every second in ReactJS?

To update a component every second in React, you can use the setInterval() method. This method takes two arguments: a callback function and a time interval in milliseconds.

Here's an example of how you can use setInterval() to update a component every second:

import React, { useState, useEffect } from 'react';
function MyComponent() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const interval = setInterval(() => {
setTime(new Date());
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>The current time is: {time.toLocaleTimeString()}</p>;
}

In this example, the useEffect() hook is used to set up an interval that will call the setTime() function every 1000 milliseconds (or 1 second). This will cause the component to re-render with the current time whenever the setTime() function is called.

It's important to note that the useEffect() hook also includes a cleanup function that will be called when the component unmounts. This cleanup function is used to clear the interval so that it doesn't continue to run even after the component is no longer being rendered.

This is just one way to update a component every second in React, but there may be other approaches that you could use depending on your specific needs.


October 18, 2022
27417