State Management
useCountdown
Manages a countdown timer with start, stop, and reset controls.
About
Count down to a target timestamp and call callbacks at a configurable interval.
Examples
Basic example
import { useCountdown } from "rooks";
export default function App() {
const endTime = new Date(Date.now() + 10_000);
const count = useCountdown(endTime);
return <div>{count} seconds remaining</div>;
}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>
);
}Arguments
| Argument | Type | Description | Default value |
|---|---|---|---|
| endTime | Date | the time when the countdown should end | undefined |
| options.interval | number | milliseconds between countdown ticks | 1000 |
| options.onDown | function | (restTime, newTime) => {} callback called every interval | undefined |
| options.onEnd | function | (time) => , callback that would be called when the countdown ends | undefined |
Return Value
| Type | Description |
|---|---|
| number | rest amount of intervals it takes to count down to the endTime |