Skip to content

useCountDown

Counts down to a target time and returns formatted remaining parts.

Counts down to a target time and returns formatted remaining parts.

Import

import { useCountDown } from '@kamod-ch/hooks'

Live demo

Basic demo

Counts down to a target time and returns formatted remaining parts.

Milliseconds left: 5000

Seconds: 5

import { useState } from 'preact/hooks'
import { useCountDown } from '@kamod-ch/hooks'

export default function UseCountDownDemo() {
  const [target, setTarget] = useState(() => Date.now() + 5000)
  const [left, formatted] = useCountDown({ targetDate: target })

  return (
    <div>
      <p><strong>Milliseconds left:</strong> {left}</p>
      <p><strong>Seconds:</strong> {formatted.seconds}</p>
      <button type="button" onClick={() => setTarget(Date.now() + 5000)}>Restart 5 second countdown</button>
    </div>
  )
}

API

TypeScript signature
export type TDate = string | number | Date | undefined;
export interface Options {
    leftTime?: number;
    targetDate?: TDate;
    interval?: number;
    onEnd?: () => void;
}
export interface FormattedRes {
    days: number;
    hours: number;
    minutes: number;
    seconds: number;
    milliseconds: number;
}
declare const useCountdown: (options?: Options) => readonly [number, FormattedRes];
export default useCountdown;
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.