Learnitweb

How to update a component every second in react?

You can update a React component every second using useEffect with setInterval in a functional component. Here’s an example:

Example: Updating a Component Every Second

import React, { useState, useEffect } from "react";

function Timer() {
  const [time, setTime] = useState(new Date().toLocaleTimeString());

  useEffect(() => {
    const interval = setInterval(() => {
      setTime(new Date().toLocaleTimeString());
    }, 1000);

    return () => clearInterval(interval); // Cleanup interval on component unmount
  }, []);

  return <h2>Current Time: {time}</h2>;
}

export default Timer;

Explanation:

  1. useState initializes the time state.
  2. useEffect runs once when the component mounts ([] as dependency).
  3. setInterval updates the time state every second.
  4. Cleanup function (clearInterval) prevents memory leaks when the component unmounts.