one-hook
Size
0.93 kb
View source

useCountdown

Countdown utility based on useInterval.

Installation

npm install @1hook/use-countdown

Usage

import {  } from '@1hook/use-countdown'

Get the remaining milliseconds:

const  = ({
  : '2026-01-01',
})

Transform the remaining time in seconds:

const  = ({
  : '2026-01-01',
  : () => .( / 1000),
})

Use a custom interval between each tick:

const  = ({
  : '2026-01-01',
  : 100,
})

Prevent rerendering the component on every tick:

({
  : '2026-01-01',
  : false,
  : () => .(),
})

Synchronize all countdowns using the same interval:

const  = ({
  : '2026-01-01',
  : true,
})

Add more details on the current countdown state:

const { ,  } = ({
  : '2026-01-01',
  (, ) {
    const  = .( / 1000)
    return {
      :  ? ( <= 0 ? 'expired' : 'ticking') : 'idle',
      ,
    }
  },
})

Background Tabs

Browsers throttle intervals in background tabs, which can leave the countdown stale. When the tab becomes visible again, the countdown immediately resamples the remaining time and triggers onTick.

API Reference

UseCountdownOptions

The options of the `useCountdown` hook.

PropTypeDefault
sync?
boolean
false
trackState?
boolean
true
onExpire?
(() => void)
-
onTick?
((value: T) => void)
-
transform?
((ms: number, to: To) => T)
-
interval?
number | ((remainingMs: number) => number)
1000
to
Date | string | null | undefined | false
-

On this page