javascriptreactjsfunctiondatetimer

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>
}

Solution

  • 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.