TimerBeginnerSSR-safehooks/timer/useCountdown.ts

useCountdown

Count down to zero.

Import

TypeScript
import { useCountdown } from '@/hooks';

API

Signature

useCountdown(initial, options?) → { count, start, stop, reset, ... }

When to use

Use useCountdown 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 · useCountdown
Editor
function OtpTimer() {
  const { count, isRunning, reset, start } = useCountdown(60, {
    onEnd: () => console.log('resend allowed'),
  });
  return (
    <button disabled={isRunning} onClick={() => { reset(60); start(); }}>
      {isRunning ? count + 's' : 'Resend'}
    </button>
  );
}
Preview

Implementation source

Full library source for useCountdown — copy into your project when you are not installing a package yet.

hooks/timer/useCountdown.ts
import { useCallback, useEffect, useState } from 'react';
import { useInterval } from './useInterval';

export interface UseCountdownOptions {
  /** Countdown interval in ms. @default 1000 */
  intervalMs?: number;
  /** Autostart. @default true */
  autoStart?: boolean;
  /** Called when countdown reaches 0. */
  onEnd?: () => void;
}

export interface UseCountdownReturn {
  count: number;
  isRunning: boolean;
  start: () => void;
  stop: () => void;
  reset: (next?: number) => void;
  pause: () => void;
  resume: () => void;
}

/** Countdown timer from an initial number down to 0. */
export function useCountdown(
  initialCount: number,
  options: UseCountdownOptions = {},
): UseCountdownReturn {
  const { intervalMs = 1000, autoStart = true, onEnd } = options;
  const [count, setCount] = useState(initialCount);
  const [isRunning, setIsRunning] = useState(autoStart && initialCount > 0);

  const stop = useCallback(() => setIsRunning(false), []);
  const pause = stop;

  const start = useCallback(() => {
    if (count > 0) setIsRunning(true);
  }, [count]);

  const resume = start;

  const reset = useCallback(
    (next = initialCount) => {
      setCount(next);
      setIsRunning(autoStart && next > 0);
    },
    [initialCount, autoStart],
  );

  useInterval(
    () => {
      setCount((c) => {
        if (c <= 1) {
          setIsRunning(false);
          onEnd?.();
          return 0;
        }
        return c - 1;
      });
    },
    isRunning ? intervalMs : null,
    { autoStart: true },
  );

  useEffect(() => {
    if (count <= 0) setIsRunning(false);
  }, [count]);

  return { count, isRunning, start, stop, reset, pause, resume };
}

Copy-paste example

useCountdown.example.tsx
'use client';

import { useCountdown } from '@/hooks';

export function OtpTimer() {
  const { count, isRunning, reset, start } = useCountdown(60, {
    onEnd: () => console.log('resend allowed'),
  });
  return (
    <button disabled={isRunning} onClick={() => { reset(60); start(); }}>
      {isRunning ? count + 's' : 'Resend'}
    </button>
  );
}

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/useCountdown.ts for implementation details