Skip to content

useCountdown

Category
Export Size
670 B
Last Changed
5 days ago

Reactive countdown timer in seconds

Demo

Usage

tsx
import { 
useCountdown
} from '@reause/core'
const
countdownSeconds
= 5
const [
remaining
,
setRemaining
, {
start
,
stop
,
pause
,
resume
}] =
useCountdown
(
countdownSeconds
, {
onComplete
() {
},
onTick
() {
} })
start
() // begins counting down from 5
setRemaining
(10) // jump to 10 on the next render

You can use a ref to change the initial countdown. start() and resume() also accept a new countdown value for the next countdown.

tsx
import { 
useCountdown
} from '@reause/core'
const
countdown
= {
current
: 5 }
const [, , {
start
,
reset
}] =
useCountdown
(
countdown
)
// change the countdown value
countdown
.
current
= 10
// start a new countdown with 2 seconds
start
(2)
// reset the countdown to 4, but do not start it
reset
(4)
// start the countdown with the current value of `countdown`
start
()

Type Declarations

ts
export interface UseCountdownOptions {
    interval?: number;
    onComplete?: () => void;
    onTick?: () => void;
}

export type UseCountdownReturn = readonly [
    remaining: number,
    setRemaining: Dispatch<SetStateAction<number>>,
    controls: {
        reset: (countdown?: number) => void;
        stop: () => void;
        start: (countdown?: number) => void;
        pause: () => void;
        resume: () => void;
        isActive: boolean;
    }
]

export function useCountdown(initialCountdown: number, options?: UseCountdownOptions): UseCountdownReturn

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
54ba1 - fix(core): resolve useCountdown audit findings (#534)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8