|Kit

useNow

The current time as a Date, re-rendering once a minute on the minute. SSR-safe, and frozen when you pass a fixed time.

useNow returns the current time and re-renders the component when the minute changes. It ticks on the system clock's minute boundary — at 10:42:00, not 60 seconds after the component mounted — so a clock or a "now" line flips at the same moment as the one in the menu bar. It is the clock behind Schedule's now line and NextUp.

import { useNow } from '@42-central/ui-react';

const now = useNow();

Usage

Ticks on the next minute.

--:--

Code

const now = useNow();
const time = new Intl.DateTimeFormat(locale, { timeStyle: 'short', timeZone }).format(now);

<p>{isNowPending(now) ? '--:--' : time}</p>

Freezing the time

Pass a Date to freeze the hook at that time. No timer runs. Use it for tests, screenshots and stories, or to give your own component a now prop:

function Agenda({ now: nowProp }: { now?: Date }) {
  const now = useNow(nowProp); // live unless the caller pins it
}

Keep the frozen Date stable (from a prop, state or useMemo). A new Date(...) written inline in render is a new object on each render.

API

function useNow(override?: Date): Date
function isNowPending(date: Date): boolean

Prop

Type

Returns a Date. A new object arrives once a minute, so it works as an effect dependency. Seconds are not tracked: a countdown or a stopwatch needs its own timer.

SSR

A server can't know the time at which the browser will hydrate, so on the server and during the hydration render useNow returns a placeholder, 1 January 1970 00:00 UTC. The real time replaces it right after hydration. isNowPending(now) is true for exactly that placeholder:

  • When rendering, show a skeleton or --:-- while it is pending, as the demo does, or the first frame reads 1970.
  • In effects that act on the time of day — scrolling a grid to the current hour, picking "Good morning" — return early while it is pending.
useEffect(() => {
  if (isNowPending(now)) return;
  scrollToHour(now.getHours());
}, [now]);

isNowPending compares identity, so a frozen useNow(new Date(0)) is not pending: it is a time you chose. In an app rendered only in the browser, the first render already has the real time and nothing is ever pending.

On this page