GooseUI

Components

useNow

New

useNow returns the current time and refreshes it on an interval. All components that ask for the same interval share one timer, and the server render never disagrees with the client.

Preview

Local time
--:--:--
On this page
0s

Installation

npx shadcn@latest add @gooseui/use-now
pnpm dlx shadcn@latest add @gooseui/use-now
yarn dlx shadcn@latest add @gooseui/use-now
bunx --bun shadcn@latest add @gooseui/use-now

Usage

import { useNow } from "@/hooks/use-now"

export function Clock() {
  const now = useNow(1000)

  // null on the server and during hydration
  if (now === null) return <span>--:--:--</span>

  return <span>{new Date(now).toLocaleTimeString()}</span>
}

Examples

Countdown

Compute the remaining time from now on every render. No local state or effects needed.

Waiting for the browser…

function Countdown({ deadline }: { deadline: number }) {
  const now = useNow(1000)
  if (now === null) return null

  const left = Math.max(0, deadline - now)
  const minutes = Math.floor(left / 60_000)
  const seconds = Math.floor((left % 60_000) / 1000)

  return <span>{minutes}:{String(seconds).padStart(2, "0")}</span>
}

One timer for many components

Each tile calls useNow(1000) on its own, but there is only one setInterval behind them, so they tick in sync.

00
00
00
function Tile() {
  const now = useNow(1000)
  return <div>{now === null ? "00" : new Date(now).getSeconds()}</div>
}

// three components, one timer
<Tile />
<Tile />
<Tile />

Coarse updates

Labels like “5 minutes ago” do not need a tick every second. Pass a larger interval to re-render less often.

function LastSeen({ at }: { at: number }) {
  // re-render once a minute
  const now = useNow(60_000)
  if (now === null) return null

  const minutes = Math.round((now - at) / 60_000)
  return <span>{minutes} min ago</span>
}

Parameters

NameTypeDefaultDescription
intervalnumber1000Refresh period in ms. Components with the same interval share one timer

Returns

TypeDescription
number | nullCurrent time in ms (like Date.now()). null on the server and during hydration

Features

  • Shared ticker. One setInterval per interval value, stopped when the last subscriber unmounts
  • Hydration-safe. Built on useSyncExternalStore with a null server snapshot, so markup always matches
  • Catches up after background. Browsers throttle timers in hidden tabs, so the value refreshes as soon as the tab is visible again