shadcn-ahooks

useCountDown

A hook for manage countdown.

Overview

A hook for manage countdown.

Documentation and Examples

Installation

Open in
pnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useCountDown.json
npx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useCountDown.json
yarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useCountDown.json
bun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useCountDown.json

A hook for manage countdown.

Countdown to target time

Dynamic config

Config leftTime

API

type TDate = Date | number | string | undefined;

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

const [countdown, formattedRes] = useCountDown(
  {
    leftTime,
    targetDate,
    interval,
    onEnd
  }
);

Remark

The precision of useCountDown is milliseconds, which may cause the following problems

  • Even if the interval time is set to 1000ms, the update interval of useCountDown may not be exactly 1000ms, but around it.
  • In the second demo, countdown is generally 499x milliseconds at the beginning due to the execution delay of the program.

If you only need to be accurate to the second, you can use it like this Math.round(countdown / 1000).

If both leftTime and targetDate are passed, the targetDate is ignored, the leftTime is dominant.

Params

| Property | Description | Type | Default | | | ----- | | countdown | Timestamp to targetDate, in milliseconds | number | | formattedResult | Formatted countdown | FormattedRes |

Remark

leftTimetargetDateintervalonEnd support dynamic change.

On this page