import { useEffect, useState } from 'react' import { relativeTime, type DateProps } from '../utils/date' import dayjs from '../utils/dayjs' const MINUTE = 60 const HOUR = MINUTE * 60 const DAY = HOUR * 24 export function useLiveRelativeTime(date: DateProps) { const [timeNow, setTimeNow] = useState(Date.now()) useEffect(() => { const tick = () => { const then = dayjs(date).valueOf() const seconds = Math.round(Math.abs(timeNow - then) / 1000) const periodInMinutes = seconds < HOUR ? 1 : seconds < DAY ? 60 : 0 if (periodInMinutes) { return setTimeout(() => setTimeNow(Date.now()), periodInMinutes * 60000) } return 0 } const timeoutId = tick() return () => { if (timeoutId) { clearTimeout(timeoutId) } } }, [date, timeNow]) useEffect(() => { setTimeNow(Date.now()) }, [date]) return relativeTime(date) }