use-countdown

Counts down to a target date or from a given duration

Usage

use-countdown counts down from a given duration (countStart) or to a target date (targetDate). It returns the remaining time in milliseconds and the same value split into days, hours, minutes, seconds and milliseconds.

With countStart, the countdown does not start automatically – call start to begin. Once it reaches 0, calling start again restarts it from countStart:

import { Button } from '@mantine/core';
import { useCountdown } from '@mantine/hooks';

function Demo() {
  const { count, running, start } = useCountdown({
    countStart: 30_000,
    interval: 1000,
  });

  const seconds = Math.ceil(count / 1000);

  return (
    <Button onClick={start} disabled={running} w={220}>
      {running ? `Resend code in ${seconds}s` : 'Resend code'}
    </Button>
  );
}

Count down to a target date

Pass targetDate (Date, timestamp or date string) to count down to a specific moment. In this mode, the countdown starts automatically:

00

Days

00

Hours

00

Minutes

00

Seconds

import { useState } from 'react';
import { Group, Paper, Stack, Text } from '@mantine/core';
import { useCountdown } from '@mantine/hooks';

function Segment({ value, label }: { value: number; label: string }) {
  return (
    <Paper withBorder p="md" radius="md" w={70}>
      <Stack align="center" gap={2}>
        <Text fw={700} fz={28} ff="monospace">
          {value.toString().padStart(2, '0')}
        </Text>
        <Text c="dimmed" size="xs" tt="uppercase">
          {label}
        </Text>
      </Stack>
    </Paper>
  );
}

function Demo() {
  const [targetDate] = useState(() => new Date(Date.now() + 2 * 24 * 3600 * 1000 + 8_130_000));
  const { formatted } = useCountdown({ targetDate });

  return (
    <Group justify="center">
      <Segment value={formatted.days} label="Days" />
      <Segment value={formatted.hours} label="Hours" />
      <Segment value={formatted.minutes} label="Minutes" />
      <Segment value={formatted.seconds} label="Seconds" />
    </Group>
  );
}

Controls

Use start, stop and reset functions to control the countdown. start resumes a stopped countdown from the current count. Changing countStart while the countdown is not running resets count to the new value:

10s

Running: no

import { Button, Group, Stack, Text } from '@mantine/core';
import { useCountdown } from '@mantine/hooks';

function Demo() {
  const { count, running, start, stop, reset } = useCountdown({
    countStart: 10_000,
    interval: 1000,
  });

  return (
    <Stack align="center">
      <Text fz={32} fw={700} ff="monospace">
        {Math.ceil(count / 1000)}s
      </Text>
      <Group>
        <Button onClick={start} disabled={running}>
          Start
        </Button>
        <Button onClick={stop} disabled={!running} variant="default">
          Stop
        </Button>
        <Button onClick={reset} variant="default">
          Reset
        </Button>
      </Group>
      <Text size="sm" c="dimmed">
        Running: {running ? 'yes' : 'no'}
      </Text>
    </Stack>
  );
}

Interval and sub-second precision

interval option controls how often the countdown updates (1000ms by default). Use a smaller interval to display milliseconds:

5.000

import { Button, Stack, Text } from '@mantine/core';
import { useCountdown } from '@mantine/hooks';

function Demo() {
  const { formatted, reset, start } = useCountdown({
    countStart: 5000,
    interval: 30,
    autoStart: true,
  });

  const restart = () => {
    reset();
    start();
  };

  return (
    <Stack align="center">
      <Text fz={32} fw={700} style={{ fontVariantNumeric: 'tabular-nums' }}>
        {formatted.seconds}.{formatted.milliseconds.toString().padStart(3, '0')}
      </Text>
      <Button onClick={restart}>Restart</Button>
    </Stack>
  );
}

The remaining time is computed from the end timestamp, so the countdown does not drift when ticks are delayed, for example in background tabs.

onComplete and onTick

onComplete is called once when the countdown reaches 0, onTick is called on every tick with the remaining number of milliseconds:

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

function Demo() {
  useCountdown({
    countStart: 10_000,
    interval: 1000,
    autoStart: true,
    onTick: (count) => console.log('Remaining', count),
    onComplete: () => console.log('Done'),
  });

  return null;
}

API

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

const { count, formatted, running, start, stop, reset } = useCountdown({
  countStart: 30_000,
  interval: 1000,
});

Options:

  • targetDate – date to count down to (mutually exclusive with countStart)
  • countStart – duration in milliseconds to count down from
  • interval – amount of milliseconds between each tick, 1000 by default
  • autoStart – whether to start automatically, true for targetDate, false for countStart
  • onComplete – called once when the countdown reaches 0
  • onTick – called on every tick with the remaining milliseconds

Return object:

  • count – remaining time in milliseconds, never less than 0
  • formatted – count split into days, hours, minutes, seconds and milliseconds
  • running – whether the countdown is currently running
  • start – starts or resumes the countdown
  • stop – stops the countdown and keeps the current count
  • reset – stops the countdown and resets count to countStart or to the time remaining until targetDate

Definition

interface UseCountdownFormatted {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
  milliseconds: number;
}

interface UseCountdownOptions {
  targetDate?: Date | number | string;
  countStart?: number;
  interval?: number;
  autoStart?: boolean;
  onComplete?: () => void;
  onTick?: (count: number) => void;
}

interface UseCountdownReturnValue {
  count: number;
  formatted: UseCountdownFormatted;
  running: boolean;
  start: () => void;
  stop: () => void;
  reset: () => void;
}

function useCountdown(options?: UseCountdownOptions): UseCountdownReturnValue

Exported types

UseCountdownOptions, UseCountdownReturnValue and UseCountdownFormatted types are exported from the @mantine/hooks package, you can import them in your application:

import type {
  UseCountdownOptions,
  UseCountdownReturnValue,
  UseCountdownFormatted,
} from '@mantine/hooks';