useCountdown
A React hook that counts down to a date or timestamp and returns days, hours, minutes, seconds and milliseconds left, with pause, resume and reset. Ticks align to whole seconds and read the clock each time, so slow or background tabs do not drift; onComplete fires once per run. The preview has a launch countdown with pause and reset and a one-time-code form whose resend link unlocks when its 30-second timer ends.
Source
import * as React from "react";
export interface UseCountdownOptions {
/** Tick length in ms. Ticks are aligned to whole intervals so seconds flip on time. Default 1000. */
interval?: number;
/** Start counting straight away. Default true. */
autoStart?: boolean;
/** Called once each time the countdown reaches zero. */
onComplete?: () => void;
}
export interface Countdown {
days: number;
hours: number;
minutes: number;
seconds: number;
/** Milliseconds left. */
remaining: number;
isRunning: boolean;
isComplete: boolean;
pause: () => void;
resume: () => void;
/** Restarts toward `next` (a Date or epoch ms), or toward the original target. */
reset: (next?: Date | number) => void;
}
const toTime = (value: Date | number | null | undefined) => (value == null ? null : value instanceof Date ? value.getTime() : value);
/**
* Counts down to `target` (a Date or epoch milliseconds). Pausing freezes the time left; resuming continues from it.
* Time is read from the clock on every tick, so background tabs and slow timers never drift.
*
* Pass a stable target (a constant, state or useMemo). A new Date built on every render restarts the countdown;
* for "30 seconds from now", keep the target in state or call reset(Date.now() + 30_000).
*/
export function useCountdown(target: Date | number | null, { interval = 1000, autoStart = true, onComplete }: UseCountdownOptions = {}): Countdown {
const targetTime = toTime(target);
const [deadline, setDeadline] = React.useState(targetTime);
// Milliseconds left while paused; null while running.
const [frozen, setFrozen] = React.useState<number | null>(() => (autoStart || targetTime === null ? null : Math.max(0, targetTime - Date.now())));
const [now, setNow] = React.useState(() => Date.now());
const onCompleteRef = React.useRef(onComplete);
onCompleteRef.current = onComplete;
const completed = React.useRef<number | null>(null);
// Follow changes to the target prop.
React.useEffect(() => {
setDeadline(targetTime);
setNow(Date.now());
setFrozen(autoStart || targetTime === null ? null : Math.max(0, targetTime - Date.now()));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [targetTime]);
React.useEffect(() => {
if (frozen !== null || deadline === null) return;
let timer: ReturnType<typeof setTimeout>;
const tick = () => {
const time = Date.now();
setNow(time);
const left = deadline - time;
if (left <= 0) return;
timer = setTimeout(tick, left % interval || interval);
};
tick();
return () => clearTimeout(timer);
}, [deadline, frozen, interval]);
const remaining = frozen ?? (deadline === null ? 0 : Math.max(0, deadline - now));
const isComplete = deadline !== null && remaining === 0;
React.useEffect(() => {
if (!isComplete || completed.current === deadline) return;
completed.current = deadline;
onCompleteRef.current?.();
}, [isComplete, deadline]);
const pause = React.useCallback(() => {
setFrozen((current) => current ?? (deadline === null ? 0 : Math.max(0, deadline - Date.now())));
}, [deadline]);
const frozenRef = React.useRef(frozen);
frozenRef.current = frozen;
const resume = React.useCallback(() => {
const left = frozenRef.current;
if (left === null) return;
setDeadline(Date.now() + left);
setNow(Date.now());
setFrozen(null);
}, []);
const reset = React.useCallback(
(next?: Date | number) => {
const time = next === undefined ? targetTime : toTime(next);
completed.current = null;
setDeadline(time);
setNow(Date.now());
setFrozen(autoStart || time === null ? null : Math.max(0, time - Date.now()));
},
[targetTime, autoStart],
);
// Round up so the display reads 0:30 at the start and 0:00 only when time is up.
const totalSeconds = Math.ceil(remaining / 1000);
return {
days: Math.floor(totalSeconds / 86_400),
hours: Math.floor((totalSeconds % 86_400) / 3600),
minutes: Math.floor((totalSeconds % 3600) / 60),
seconds: totalSeconds % 60,
remaining,
isRunning: frozen === null && deadline !== null && remaining > 0,
isComplete,
pause,
resume,
reset,
};
}
