Categories
React Answers

How to update React component every second with JavaScript?

Spread the love

Sometimes, we want to update React component every second with JavaScript.

In this article, we’ll look at how to update React component every second with JavaScript.

How to update React component every second with JavaScript?

To update React component every second with JavaScript, we can use the setInterval function to update a state in the useEffect hook.

For instance, we write

const [time, setTime] = useState(Date.now());

useEffect(() => {
  const interval = setInterval(() => setTime(Date.now()), 1000);
  return () => {
    clearInterval(interval);
  };
}, []);

in a function component.

We get set the initial value of time to the timestamp returned by Date.now.

Then in the useEffect callback, we call setInterval with a callback that calls setTime with Date.now() to update the time to the current timestamp.

And we call it with 1000 to do that every second.

We return a callback that calls clearInterval with interval to clear the timer when we unmount our component.

The useEffect callback runs once when we mount our component since we called it with an empty array.

Conclusion

To update React component every second with JavaScript, we can use the setInterval function to update a state in the useEffect hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *