import { useEffect, useState } from 'react' /** Milliseconds until the next local midnight, plus a small buffer. */ function msUntilNextLocalDay(now: Date): number { const nextMidnight = new Date(now) nextMidnight.setHours(24, 0, 0, 0) return nextMidnight.getTime() - now.getTime() + 5_000 } /** * The current date, refreshed when the local day changes (via a timer set to * the next midnight) and when the tab regains focus. Components selling a * "today only" view use it so bought items disappear once the day rolls over * even if the page has been open all night. */ export function useToday(): Date { const [today, setToday] = useState(() => new Date()) useEffect(() => { const refresh = () => setToday(new Date()) const timer = setTimeout(refresh, msUntilNextLocalDay(new Date())) window.addEventListener('focus', refresh) document.addEventListener('visibilitychange', refresh) return () => { clearTimeout(timer) window.removeEventListener('focus', refresh) document.removeEventListener('visibilitychange', refresh) } }, []) return today }