Getting started
npm install @crup/react-timer-hook@latest
pnpm add @crup/react-timer-hook@latest
Runtime requirements: Node 18+ and React 18+.
import { useTimer } from '@crup/react-timer-hook';
import { durationParts } from '@crup/react-timer-hook/duration';
import { useTimerGroup } from '@crup/react-timer-hook/group';
import { useScheduledTimer } from '@crup/react-timer-hook/schedules';
import type { TimerSnapshot } from '@crup/react-timer-hook';
First timer
import { useTimer } from '@crup/react-timer-hook';
import { durationParts } from '@crup/react-timer-hook/duration';
export function BreakTimer() {
const durationMs = 5 * 60 * 1000;
const timer = useTimer({
autoStart: true,
updateIntervalMs: 1000,
endWhen: snapshot => snapshot.elapsedMilliseconds >= durationMs,
});
const remaining = durationParts(durationMs - timer.elapsedMilliseconds);
return (
<span>
{remaining.minutes}:{String(remaining.seconds).padStart(2, '0')}
</span>
);
}
Use timer.now for wall-clock work such as absolute deadlines and clocks.
Use timer.elapsedMilliseconds for active elapsed work such as stopwatches and pausable duration countdowns.
Use endWhen to describe when a lifecycle should end. Use cancel(reason) for terminal early stops that should not call onEnd.