Abhay Rohit
Abhay Rohit

Reputation: 55

Creating Clock in React

I have a website and I want to put a realtime clock on one of the pages. I have written the code using hooks but I understand using hooks for such cases is bad for performance due to rerenders in states every second. Is there a less resource intensive solution?

import { useEffect, useState } from 'react'

export default function Footer() {
  const [time, setTime] = useState()

  useEffect(() => {

    setInterval(() => {

      const dateObject = new Date()

      const hour = dateObject.getHours()
      const minute = dateObject.getMinutes()
      const second = dateObject.getSeconds()

      const currentTime = hour + ' : ' + minute + ' : ' + second
      
      setTime(currentTime)
    }, 1000)

  }, [])

  return <div>{time}</div>
}

Upvotes: 1

Views: 6739

Answers (3)

leonardo sena
leonardo sena

Reputation: 21

const Clock = ()=>{

 var [time, setTime] = useState("00:00:00");
useMemo(() => {

        var x = setInterval(() => { setHora(new Date().toLocaleTimeString()) }, 500)
        setTime(x);
    }, [setHora]);
}

Upvotes: 2

Smit lathiya
Smit lathiya

Reputation: 65

const Clock = () => {
    const [date, setDate] = useState(new Date());
    useEffect(() => {
        const timerID = setInterval(() => tick(), 1000);
        return () => clearInterval(timerID);
    }, []);

    const tick = useCallback(() => {
        setDate(new Date());
    }, []);

    const options: any = { hour: "2-digit", minute: "2-digit", hour12: false };
    const timeString = useMemo(() => date.toLocaleTimeString("en-GB", options), [date]);

    return <span>{timeString}</span>;
};

Upvotes: 0

darthgoldstein
darthgoldstein

Reputation: 112

It's definitely good that you're thinking about performance however in this situation I wouldn't change a single thing. In order to change what gets rendered to the screen (in this case the text of the clock), the component has to be re-rendered to reflect the change in it's state, which is not such a bad thing. Each time the component re-renders it's not going to cause the parent to re-render so performance-wise we're doing just fine.

Upvotes: 1

Related Questions