useToday
Today's date that rolls over at midnight and when the tab comes back, without a hydration mismatch.
pnpm dlx shadcn@latest add https://hextaui.com/r/use-today.jsonAdds the hook and anything it depends on to your project.
Copy and paste the following code into your project.
hooks/use-today.ts Update the import paths to match your project setup.
Reach for it whenever a component depends on the current date, such as highlighting today, disabling past days or counting down to a deadline.
Reading the date while rendering breaks in two ways:
- Hydration mismatches. The server renders in its time zone, possibly hours earlier. Near midnight, server and browser disagree on the day, and React throws away the server HTML.
- Stale dates. A tab left open overnight keeps showing yesterday as today until something else re-renders it.
useToday returns undefined on the server and during hydration, then the local date. It also re-renders at midnight and when the tab becomes visible again, because timers in background tabs can be paused and miss midnight.
Date bounds
Disable past days and anything more than 30 days out. Until today is known, nothing is disabled, so the server HTML matches the first client render.
| Su | Mo | Tu | We | Th | Fr | Sa |
|---|---|---|---|---|---|---|
The file also exports the pieces the hook is built from. Date keys are local YYYY-MM-DD strings. They compare by day, sort correctly and are safe to use as React keys or cache keys. subscribeToday calls you back at midnight and on tab return, outside React.
- The returned
Dateis midnight in local time, so comparing it with<or>compares days, not times. - The same
Dateobject comes back until the day changes, so it's safe to use in effect dependencies. - Plan for the
undefinedrender. A skeleton, or rendering without date-based limits, both work.
| Returns | Description |
|---|---|
Date | undefined | Local midnight today. undefined on the server and while hydrating. |
| Export | Description |
|---|---|
toDateKey(date) | A Date as a local YYYY-MM-DD string. |
fromDateKey(key) | A YYYY-MM-DD string as a local-midnight Date. |
getTodayKey() | Today's date key. |
subscribeToday(callback) | Calls back at midnight and when the tab becomes visible. Returns an unsubscribe function. |
Calendar, and Date picker through it.