NoteThis hook uses a reference timestamp approach rather than a simple counter. This prevents "time drift," ensuring the countdown stays accurate even if the browser's event loop is busy.
TipYou can use the increment control to add "bonus time" to a game or session without resetting the entire countdown logic.
The useCountDown manages time remaining by comparing the current system clock against a target absolute timestamp. This approach eliminates cumulative time drift caused by setInterval execution delays, ensuring sub-second accuracy even during heavy main-thread activity or browser tab throttling.
The hook provides explicit lifecycle management via a status state and memoized control functions. It supports manual starting, pausing, resetting, and dynamic time increments, making it suitable for complex timing logic like game loops, persistent timers, or transaction expirations.
| Name | Type | Description |
|---|---|---|
| endTime | number | The target Unix timestamp (ms) to count down to. |
| startOnMount | boolean | Whether the timer starts automatically on component mount. Default: false. |
| options.interval | number | Frequency of UI updates in milliseconds. Default: 1000. |
| options.onTick | (time: number) => void | Callback triggered on every tick with the current remaining time. |
| options.onComplete | () => void | Callback triggered once the remaining time reaches zero. |
| Name | Type | Description |
|---|---|---|
| count | number | The current remaining time in milliseconds. |
| status | string | The current status of the timer. Status types are 'start', 'running', 'paused', and 'completed'. |
| controls.start | () => void | Initiates the countdown if status is 'start' |
| controls.pause | () => void | Pauses the timer and stores the remaining duration. |
| controls.resume | () => void | Resumes a paused timer by calculating a new end timestamp. |
| controls.reset | () => void | Clears the timer and reverts to the initial duration. |
| controls.increment | (ms?: number) => void | Adds the specified milliseconds to the current countdown. |