# 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

```ts
import { useNow } from '@vincent.ri/react-tils'
// or only this hook
import { useNow } from '@vincent.ri/react-tils/useNow'
```

## Usage

```ts
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)
```

## 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

```ts
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

Works in all modern browsers.

---

153 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useNow.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useNow/
Previous: [useHydrated](https://vincentri.github.io/react-tils/hooks/useHydrated.md)
Next: [usePageRestore](https://vincentri.github.io/react-tils/hooks/usePageRestore.md)
