All hooks / Page, device, and user
useNow
The current time as a timestamp in milliseconds, rounded down to intervalMs and updated every intervalMs. Ticks land on whole intervals (a 1000 ms clock changes exactly on the second), so every component using the same interval shows the same time.
The server and the client never agree on the time, so new Date() in render causes a hydration mismatch. This hook returns serverValue (default null) on the server and during hydration, then the real time.
Import
import { useNow } from '@vincent.ri/react-tils'
// or only this hook
import { useNow } from '@vincent.ri/react-tils/useNow'Usage
const now = useNow(1000)
return <time>{now === null ? '--:--:--' : new Date(now).toLocaleTimeString()}</time>
// Relative time, updated every minute.
const now = useNow(60_000)
const minutes = now === null ? 0 : Math.round((now - sentAt) / 60_000)Live demo
A clock with no hydration mismatch: placeholder in the server HTML.
When to use it
A clock, a countdown, "5 minutes ago" labels, or anything else that renders the current time.
When not to
You need to run code on a schedule rather than render the time; use useInterval. For a time read once, call Date.now() in an event handler.
API
function useNow<S extends number | null = null>(intervalMs: number, serverValue?: S): number | S| Parameter | Description |
|---|---|
intervalMs | How often to update, and the precision of the value. |
serverValue | Value on the server and during hydration, e.g. the request time passed from the server. Default null. |
Browser support
Uses only long-established browser features, so it works wherever React does.
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).