@luwiostack/clock
v0.2.0
Published
An injectable clock — SystemClock / TimezoneAwareClock / MockClock over @luwiostack/datetime (React-free), with optional React bindings: <Clock> / <SystemClock> / <TimezoneClock> providers and useNow / useToday / useClock hooks.
Readme
@luwiostack/clock
An injectable clock — a source of "now" you pass in rather than reach for globally, so time is
testable and can be pinned to a timezone. Built on @luwiostack/datetime
(DateTime.now, and the Timezone it re-exports from @luwiostack/timezone).
Part of LuwioStack — the date/time family (date/time in @luwiostack/datetime,
@luwiostack/timezone, @luwiostack/clock).
Install
npm install @luwiostack/clock @luwiostack/datetimereact is an optional peer — needed only for @luwiostack/clock/react.
Two entry points
@luwiostack/clock— the React-free domain:SystemClock,TimezoneAwareClock,MockClock.@luwiostack/clock/react— two providers:<Clock>/<TimezoneClock>(active) and<SystemClock>(host), withuseNow/useToday/useTime/useClockanduseSystemNow/useSystemToday/useSystemTime/useSystemClock.
The provider <TimezoneClock timezone={…}> is the React wiring for the domain's TimezoneAwareClock
— it builds one for you (the suffix-free provider name pairs with the descriptive domain class),
while <Clock clock={…}> takes any clock you construct yourself.
Providers take the clean name, so the /react <SystemClock> provider shares its name with the root
SystemClock class (like Country / <Country>). A file rarely needs both — <SystemClock> builds
its own new SystemClock() — but when it does, alias one:
import { SystemClock as SystemClockClass } from '@luwiostack/clock'.
The read hooks (useNow / useToday / useTime and the useSystem* variants) return a snapshot
per render — they read the clock once and do not tick on their own, so they run anywhere, the
server included (but see Server rendering for hydration). For a live value, pass
{ tickMs } (e.g. useTime({ tickMs: 1000 }) for a ticking seconds display) or drive re-renders
yourself.
Usage
The device clock belongs to the user. In a browser,
SystemClock,useNow(),useToday()andInstant.now()read the visitor's own device clock, which they can set to anything. Use them for display. Never let them decide anything that matters for security — an age check (isAtLeast(18)), a token or session expiry, a trial period, a rate limit: make those decisions on the server, with the server's clock.
import { SystemClock, TimezoneAwareClock, MockClock } from '@luwiostack/clock'
import { DateTime, Timezone } from '@luwiostack/datetime'
const clock = new TimezoneAwareClock(Timezone.system) // or new SystemClock() — never throws, even on a
// misconfigured host (see Timezone.system)
clock.now() // DateTime
clock.instant() // Instant — zone-free, for timestamps like createdAt (mockable, unlike Instant.now())
clock.today() // DateOnly
clock.time() // Time
// Deterministic in tests:
const fixed = new MockClock(DateTime.fromLocalIso('2026-08-12T09:00:00.000', Timezone.new({ name: 'UTC' })))
fixed.today().toIso8601() // '2026-08-12'React
import { Clock, TimezoneClock, useNow, useToday } from '@luwiostack/clock/react'
import { SystemClock } from '@luwiostack/clock'
import { Timezone } from '@luwiostack/datetime'
// Provide a clock directly — created once, outside render: a new clock per render is a new context
// value, which re-renders every component reading it (memoized ones too). In a component, useMemo it.
const clock = new SystemClock()
<Clock clock={clock}>…</Clock>
// … or bind one to a timezone:
<TimezoneClock timezone={Timezone.system}>…</TimezoneClock>
function Header() {
const today = useToday() // DateOnly
return <time>{today.toIso8601()}</time>
}The read hooks (useNow, useToday, useTime and the useSystem* variants) are a snapshot per
render — they read the clock once and don't tick on their own. Each render returns a new object, so
in effect dependencies use a value instead: [now.toEpochMilliseconds()], or something coarser such
as [now.toTime().minute.asInt()] to run once a minute. For a live value pass { tickMs }
(a LiveOptions), e.g. useTime({ tickMs: 1000 }); it must be at least 16 milliseconds (one display
frame; a smaller, negative or non-finite value throws) and at most 100 years — a long interval, a
month say, is fine. Ticks land on whole multiples of tickMs in the clock's own wall time — for
1000, exactly as each second starts; for 86_400_000, at local midnight (DST and half-hour zones
included) — and are timed on the clock you provide, not the host machine's, so a ticking display
changes when the value does, and doesn't drift. useClock() gives the clock itself — call
.instant() on it to stamp an event.
For the timezone context itself (a <Timezone> provider + useTimezone), use
@luwiostack/timezone/react — <TimezoneClock> only wires the matching clock.
System clock + an override
Mirroring @luwiostack/timezone's two providers: mount <SystemClock> once near the root
(the host-machine clock, always available) and <Clock> / <TimezoneClock> for the active
zone. Read both to show the difference between the displayed time and the viewer's own.
import { SystemClock, TimezoneClock, useNow, useSystemNow } from '@luwiostack/clock/react'
import { TimeFormatter, Timezone } from '@luwiostack/datetime'
function App({ eventZone }: { eventZone: Timezone }) {
return (
<SystemClock>
<TimezoneClock timezone={eventZone}>
<Times />
</TimezoneClock>
</SystemClock>
)
}
function Times() {
const there = useNow() // now in the event zone
const here = useSystemNow() // now in the viewer's own zone
return (
<p>
{there.timezone.name}: {TimeFormatter.format(there.toTime(), 'HH:mm')} —
{' '}your time: {TimeFormatter.format(here.toTime(), 'HH:mm')}
</p>
)
}Custom clocks and tests
SystemClock, TimezoneAwareClock and MockClock all implement IClock — now() (a DateTime),
instant() (a zone-free Instant), today() (a DateOnly) and time() (a Time). Implement it
yourself for anything else (a server-offset-corrected clock, say) and pass it to <Clock>.
MockClock.setMockDate(dt) sets a mock clock, and advance(amount) moves it — a Duration (exact
time) or a Period (calendar time, like DateTime.add): clock.advance(Duration.minutes(5)). React
consumers see the new value on their next render — neither call triggers one itself — so re-render (or
use { tickMs }) after moving it.
Relative time and countdowns
useRelativeTime(moment, { tickMs? }) gives how far a DateTime or Instant is from the clock's now as
a translation token — { key: 'x_minutes_ago', placeholders: { x: '5' } }, or { key: 'in_an_hour' }
for the future (the TimeAgoFormatter / TimeToBeFormatter buckets; its type is RelativeTimeToken).
useCountdown(target, { tickMs? }) gives a Countdown — { remaining, isDone }, the exact Duration
left (never negative). With tickMs, both tick in step with their moment rather than the wall
clock: a countdown to 12:00:03.5 ticks at .5 past each second, so whole seconds left show as whole
seconds, and "5 minutes ago" appears exactly 5 minutes after the moment. The last tick lands on the
moment itself — the countdown is done, "in a few seconds" turns into "ago" — and a countdown stops
ticking once the target is reached. Without tickMs both are a snapshot, like the other hooks.
function Posted({ at }: { at: Instant }) {
const { key, placeholders } = useRelativeTime(at, { tickMs: 60_000 })
return <span>{t(key, placeholders)}</span>
}
function SaleEndsIn({ end }: { end: DateTime }) {
const { remaining, isDone } = useCountdown(end, { tickMs: 1000 })
return isDone ? <span>Ended</span> : <span>{DurationFormatter.formatLocale(remaining, locale, { style: 'digital' })}</span>
}The raw contexts (ClockContext, SystemClockContext) and the prop types (ClockProps,
SystemClockProps, TimezoneClockProps) are exported for advanced wiring.
Server rendering
A snapshot hook runs fine on the server, but the server's "now" and the client's "now" differ by the
time it takes the page to arrive. Read a live clock on both sides and React reports a hydration
mismatch and throws away the server HTML for that tree. Instead, render on the server with a
MockClock at the request time — for the system clock too, if you use the useSystem* hooks — send
that time with the page, hydrate with the same mock, and switch to the live clocks after mounting:
// Server: render with the request time, and send that time along with the HTML.
const requestTime = Date.now()
const zone = Timezone.new({ name: 'Europe/Brussels' }) // a zone both sides agree on
const serverClock = new MockClock(DateTime.fromEpochMilliseconds(requestTime, zone))
const html = renderToString(
<SystemClock clock={serverClock}>
<Clock clock={serverClock}>
<App />
</Clock>
</SystemClock>,
)
// …and put requestTime in the page head as a meta tag — no inline <script>, so a strict
// Content-Security-Policy (no 'unsafe-inline') allows it:
// <meta name="request-time" content="1767268800000">
// Client: hydrate with that same time, then switch to the live clocks once mounted.
function HydratingClock({ serverNow, children }: PropsWithChildren<{ serverNow: number | null }>) {
const [mock] = useState(() => {
const at = serverNow === null ? null : DateTime.tryFromEpochMilliseconds(serverNow, zone)
return at ? new MockClock(at) : null
})
const [live] = useState(() => new TimezoneAwareClock(zone))
const [mounted, setMounted] = useState(false)
useEffect(() => setMounted(true), [])
const pinned = mounted ? null : mock
return (
<SystemClock clock={pinned ?? undefined}>
<Clock clock={pinned ?? live}>{children}</Clock>
</SystemClock>
)
}
// Whole epoch milliseconds only: a missing, empty or tampered value (`Number('')` would be 0 —
// 1 January 1970) gives null, and the page starts on the live clock instead.
function readServerNow(): number | null {
const content = document.querySelector('meta[name="request-time"]')?.getAttribute('content') ?? ''
return /^\d{1,15}$/.test(content) ? Number(content) : null
}
hydrateRoot(root, <HydratingClock serverNow={readServerNow()}><App /></HydratingClock>)Use a zone both sides agree on (the event's, or the user's saved one): the server can't know the
viewer's own zone, so a SystemClock on the server would render in the server's zone. For the same
reason the system clock shows that agreed zone until the page has mounted, then the viewer's own.
