React Clock Component

Start your own chat
Write me a React Clock component that shows the current time

Sure! Below is a simple React component that displays the current time. This component updates every second to show the current time.

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

const Clock = () => {
  const [currentTime, setCurrentTime] = useState(new Date());

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

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

  return (
    <div>
      <h1>Current Time</h1>
      <p>{currentTime.toLocaleTimeString()}</p>
    </div>
  );
};

export default Clock;

Explanation:

  • State Management: We use the useState hook to manage the current time.
  • Effect Hook: The useEffect hook is used to set up a timer that updates the current time every second.
  • Cleanup: The cleanup function in useEffect ensures that the interval is cleared when the component is unmounted, preventing memory leaks.
  • Rendering: The component renders the current time formatted as a string using toLocaleTimeString().

You can include this component in your React application to display the current time.

Chat bySam Selikoff