useTimer
Countdown or stopwatch mode switch.
Import
TypeScript
import { useTimer } from '@/hooks';API
Signature
useTimer({ mode, initialCount, ... })
When to use
Use useTimer instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Timers start in effects — no server timers.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useTimerEditor
function Pomodoro() { const t = useTimer({ mode: 'countdown', initialCount: 25 * 60 }); return <p>{t.value} · {t.isRunning ? 'running' : 'paused'}</p>; }
Preview
Implementation source
Full library source for useTimer — copy into your project when you are not installing a package yet.
hooks/timer/useTimer.ts
import { useCountdown } from './useCountdown';
import { useStopwatch } from './useStopwatch';
export type UseTimerMode = 'countdown' | 'stopwatch';
export interface UseTimerOptions {
mode?: UseTimerMode;
initialCount?: number;
intervalMs?: number;
autoStart?: boolean;
onEnd?: () => void;
}
/**
* Unified timer API (countdown or stopwatch).
*/
export function useTimer(options: UseTimerOptions = {}) {
const {
mode = 'countdown',
initialCount = 60,
intervalMs,
autoStart,
onEnd,
} = options;
const countdown = useCountdown(initialCount, {
intervalMs,
autoStart,
onEnd,
});
const stopwatch = useStopwatch({ intervalMs, autoStart });
if (mode === 'stopwatch') {
return {
mode,
value: stopwatch.ms,
seconds: stopwatch.seconds,
isRunning: stopwatch.isRunning,
start: stopwatch.start,
stop: stopwatch.stop,
pause: stopwatch.pause,
resume: stopwatch.resume,
reset: stopwatch.reset,
} as const;
}
return {
mode,
value: countdown.count,
seconds: countdown.count,
isRunning: countdown.isRunning,
start: countdown.start,
stop: countdown.stop,
pause: countdown.pause,
resume: countdown.resume,
reset: countdown.reset,
} as const;
}
Copy-paste example
useTimer.example.tsx
'use client';
import { useTimer } from '@/hooks';
export function Pomodoro() {
const t = useTimer({ mode: 'countdown', initialCount: 25 * 60 });
return <p>{t.value} · {t.isRunning ? 'running' : 'paused'}</p>;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Pass null delay to pause/disable intervals and timeouts without unmounting.
- Source of truth: open
hooks/timer/useTimer.tsfor implementation details