All files / packages / hooks/src use-now.ts

100% Statements 11/11
100% Branches 0/0
100% Functions 6/6
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24      4x   4x   4x           4x   4x 4x   4x     4x    
import { useEffect, useState } from 'react'
 
function msUntilNextDay(now: number): number {
  const nextDay = new Date(now)
 
  nextDay.setHours(24, 0, 0, 0)
 
  return nextDay.getTime() - now
}
 
// The time the day labels are measured from. It moves on at each local midnight, so a tab left
// open overnight does not keep yesterday's messages under "Today".
export function useNow(): number {
  const [now, setNow] = useState(() => Date.now())
 
  useEffect(() => {
    const timer = setTimeout(() => setNow(Date.now()), msUntilNextDay(now))
 
    return () => clearTimeout(timer)
  }, [now])
 
  return now
}