Hooks
usePolling
Periodic polling that pauses in the background and catches up on return.
Periodic polling — for values not worth holding a permanent connection open for: an unread counter, the status of a background job, the number of people online.
Example
—
Опрос каждые 3 секунды. Переключитесь на другую вкладку и вернитесь — время обновится сразу, а не через интервал.
import { usePolling } from "@toimetdev/pathlogs-hooks";
const { data: count, refresh } = usePolling(
async () => {
const res = await fetch("/api/notifications/unread-count", { cache: "no-store" });
const json = await res.json();
return json.count as number;
},
{ initial: unreadFromServer, interval: 30_000 }
);The initial value comes from the server, so the counter shows the truth from the very first frame instead of flashing a zero until the first request lands.
Options
| Prop | Type | Default | Description |
|---|---|---|---|
fetcher* | () => Promise<T> | — | What to request. Errors are swallowed — we will try again next time. |
initial* | T | — | The value before the first successful request. Usually comes from the server. |
interval | number | 30000 | The polling period in milliseconds. |
pauseWhenHidden | boolean | true | Do not poll while the tab is in the background. Nobody reads a value in a tab they cannot see. |
immediate | boolean | false | Poll right on mount instead of waiting out the first interval. |
enabled | boolean | true | Disable polling without removing the hook. |
fetcher*() => Promise<T>What to request. Errors are swallowed — we will try again next time.
initial*TThe value before the first successful request. Usually comes from the server.
intervalnumberdefaults to: 30000
The polling period in milliseconds.
pauseWhenHiddenbooleandefaults to: true
Do not poll while the tab is in the background. Nobody reads a value in a tab they cannot see.
immediatebooleandefaults to: false
Poll right on mount instead of waiting out the first interval.
enabledbooleandefaults to: true
Disable polling without removing the hook.
Returns { data, refresh }. refresh goes down the same path as the timer — one entry point, one policy.
Polling versus streaming
- Polling — when the value is small, changes rarely, and a delay of tens of seconds upsets nobody. It asks nothing of the server beyond an ordinary endpoint.
- Streaming (
useEventStream) — when a change must arrive within seconds and several people see it at once: a board, comments, collaborative editing.
Holding a connection open for a number in the corner of the screen is a bad trade: you get as many connections as there are tabs, for a penny's worth of benefit.