use-countdown

Counts down to a target date or from a given duration

Usage

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

With countStart, call start to begin the countdown. Once it reaches 0, start restarts it:

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 to count down to a specific moment. 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:

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 controls how often the countdown updates, one second 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>
  );
}

onComplete and onTick

onComplete is called once when the countdown reaches 0. onTick is called on every tick with the remaining 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,
});

Definition

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

interface UseCountdownOptions {
  /** Date to count down to, cannot be used with `countStart` */
  targetDate?: Date | number | string;

  /** Duration in milliseconds to count down from */
  countStart?: number;

  /** Milliseconds between ticks, `1000` by default */
  interval?: number;

  /** Starts the countdown on mount, `true` for `targetDate`, `false` for `countStart` */
  autoStart?: boolean;

  /** Called once when the countdown reaches `0` */
  onComplete?: () => void;

  /** Called on every tick with the remaining milliseconds */
  onTick?: (count: number) => void;
}

interface UseCountdownReturnValue {
  /** Remaining time in milliseconds, never less than `0` */
  count: number;

  /** `count` split into days, hours, minutes, seconds and milliseconds */
  formatted: UseCountdownFormatted;

  /** `true` while the countdown is running */
  running: boolean;

  /** Starts or resumes the countdown */
  start: () => void;

  /** Stops the countdown and keeps the current `count` */
  stop: () => void;

  /** Stops the countdown and resets `count` to the initial value */
  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';