Rooks
State Management

useCountdown

Manages a countdown timer with start, stop, and reset controls.

About

Count down to a target timestamp and call callbacks at a configurable interval.

Examples

Basic example

import { useCountdown } from "rooks";

export default function App() {
  const endTime = new Date(Date.now() + 10_000);
  const count = useCountdown(endTime);

  return <div>{count} seconds remaining</div>;
}

Use callbacks for progress and completion

import { useState } from "react";
import { useCountdown } from "rooks";

export default function AutoDismissNotice() {
  const [events, setEvents] = useState([]);
  const count = useCountdown(new Date(Date.now() + 3_000), {
    interval: 1_000,
    onDown: (remaining) => {
      setEvents((current) => [...current, `tick:${remaining}`]);
    },
    onEnd: () => {
      setEvents((current) => [...current, "ended"]);
    },
  });

  return (
    <div>
      <p>{count === 0 ? "Dismissed" : `${count} seconds remaining`}</p>
      <pre>{JSON.stringify(events, null, 2)}</pre>
    </div>
  );
}

Arguments

ArgumentTypeDescriptionDefault value
endTimeDatethe time when the countdown should endundefined
options.intervalnumbermilliseconds between countdown ticks1000
options.onDownfunction(restTime, newTime) => {} callback called every intervalundefined
options.onEndfunction(time) => , callback that would be called when the countdown endsundefined

Return Value

TypeDescription
numberrest amount of intervals it takes to count down to the endTime

On this page