react component of a clock that has a useeffect hook that updates the clock every second in typescript

Below is the sample code for creating a React clock component with a useEffect hook that updates the clock every second in TypeScript:

index.ts
import React, { useState, useEffect } from 'react';

const Clock = () => {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    const timerID = setInterval(() => tick(), 1000);

    return function cleanup() {
      clearInterval(timerID);
    };
  });

  const tick = () => {
    setTime(new Date());
  };

  return (
    <div>
      <h1>{time.toLocaleTimeString()}</h1>
    </div>
  );
};

export default Clock;
434 chars
26 lines

In this code snippet, we have used the useState hook to create a state variable time which holds the current time.

We have then used the useEffect hook to update the time state variable every second. The useEffect hook takes in a function that is executed after every render, and we have used the setInterval function inside this function to update the time state variable every second.

We have also returned a cleanup function from the useEffect hook that clears the interval when the component is unmounted.

Finally, we have rendered the time state variable inside an h1 tag, which is displayed as the current time in the browser.

gistlibby LogSnag