Understanding React hook useEffect & best practice

I have a personal greeting component that is setup like:

const PersonalGreeting = (): ReactElement => {
  const [timeOfDay, setTimeOfDay] = useState(null)
  const [date, setDate] = useState(new Date())

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

    setTimeOfDay(getTimeOfDay(date))

    return () => {
      clearInterval(timer)
    }
  }, [date])

  return (
    <>
    Good {timeOfDay}, Name
    </>
  )
}

When I console.log outside of the useEffect function, it seems to run twice. Inside the useEffect function it runs once, I was wondering if I was setting this up incorrectly or if there was a better way of doing this.

Helper function –

const getTimeOfDay = (date: Date): string => {
  let timeOfDay = ''
  const hour = date.getHours()
  const minute = date.getMinutes()
  const isOClock = minute === 0

  if ((hour >= 4 && hour < 12) || (hour === 12 && isOClock)) {
    timeOfDay = 'Morning'
  }

  if ((hour >= 12 && !isOClock && hour < 17) || (hour === 17 && isOClock)) {
    timeOfDay = 'Afternoon'
  }

  if ((hour >= 17 && !isOClock) || hour < 4) {
    timeOfDay = 'Evening'
  }

  return timeOfDay
}

17 thoughts on “Understanding React hook useEffect & best practice”

Leave a Comment