useCountdown
Counts the intervals remaining until a target Date and reports progress or completion.
About
Count down to a target timestamp and call callbacks at a configurable interval.
Examples
Basic example
import { useState } from "react";
import { useCountdown } from "rooks";
export default function TenSecondCountdown() {
const [endTime] = useState(() => new Date(Date.now() + 10_000));
const count = useCountdown(endTime);
return <p>{count === 0 ? "Finished" : `${count} seconds remaining`}</p>;
}Use callbacks for progress and completion
import { useState } from "react";
import { useCountdown } from "rooks";
export default function AutoDismissNotice() {
const [events, setEvents] = useState([]);
const count = useCountdown(new Date(Date.now() + 3_000), {
interval: 1_000,
onDown: (remaining) => {
setEvents((current) => [...current, `tick:${remaining}`]);
},
onEnd: () => {
setEvents((current) => [...current, "ended"]);
},
});
return (
<div>
<p>{count === 0 ? "Dismissed" : `${count} seconds remaining`}</p>
<pre>{JSON.stringify(events, null, 2)}</pre>
</div>
);
}Parameters
| Argument | Type | Description | Default value |
|---|---|---|---|
| endTime | Date | Required target instant | — |
| options.interval | number | Positive milliseconds per tick | 1000 |
| options.onDown | (restTime: number, newTime: Date) => void | Called on positive-remaining-time ticks; restTime is milliseconds | — |
| options.onEnd | (newTime: Date) => void | Called once when this target is observed at or past its end | — |
Return value
| Type | Description |
|---|---|
| number | Number of whole configured intervals remaining, rounded up; 0 at or after the target |
Behavior and lifecycle
The first tick runs immediately while time remains. Each tick reads the current clock, invokes onDown before updating rendered state, and stops the interval at zero. onEnd fires once per endTime timestamp, including for an already elapsed target. Changing the callback does not restart the interval; changing the target or interval recalculates the count.
Compatibility and accessibility
Date arithmetic is SSR-safe and timers start only through React effects in the browser. Use a target supplied consistently to server and client when the initial count is rendered during hydration. Announce urgent countdown changes sparingly so screen readers are not interrupted every second.
Related
- useIntervalWhen is the interval primitive used by this hook.
- useTemporalCountdown provides Temporal-based duration and precision controls.