useCountdown()

A simple countdown implementation. Support increment and decrement.

Related hooks:

The Hook

1// See: https://usehooks-ts.com/react-hook/use-boolean
2import { useBoolean } from '../useBoolean'
3// See: https://usehooks-ts.com/react-hook/use-counter
4import { useCounter } from '../useCounter'
5// See: https://usehooks-ts.com/react-hook/use-interval
6import { useInterval } from '../useInterval'
7
8interface UseCountdownType {
9 seconds: number
10 interval: number
11 isIncrement?: boolean
12}
13interface CountdownHelpers {
14 start: () => void
15 stop: () => void
16 reset: () => void
17}
18
19/**
20 *
21 * @param seconds the countdown's number, generally time seconds
22 * @param interval the countdown's interval, milliseconds
23 * @param isIncrement determine the countdown is increment, otherwise is decrement
24 * @returns
25 */
26function useCountdown({
27 seconds,
28 interval,
29 isIncrement,
30}: UseCountdownType): [number, CountdownHelpers] {
31 const {
32 count,
33 increment,
34 decrement,
35 reset: resetCounter,
36 } = useCounter(seconds)
37 /**
38 * Note: used to control the useInterval
39 * running: If true, the interval is running
40 * start: Should set running true to trigger interval
41 * stop: Should set running false to remove interval
42 */
43 const { value: running, setTrue: start, setFalse: stop } = useBoolean(false)
44
45 /**
46 * Will set running false and reset the seconds to initial value
47 */
48 const reset = () => {
49 stop()
50 resetCounter()
51 }
52
53 useInterval(isIncrement ? increment : decrement, running ? interval : null)
54 return [count, { start, stop, reset }]
55}
56
57export default useCountdown

Usage

1import React, { ChangeEvent, useState } from 'react'
2
3import { useCountdown } from 'usehooks-ts'
4
5export default function Component() {
6 const [intervalValue, setIntervalValue] = useState<number>(500)
7 const [count, { start, stop, reset }] = useCountdown({
8 seconds: 60,
9 interval: 500,
10 isIncrement: false,
11 })
12
13 const handleChangeIntervalValue = (event: ChangeEvent<HTMLInputElement>) => {
14 setIntervalValue(Number(event.target.value))
15 }
16 return (
17 <div>
18 <p>Count: {count}</p>
19
20 <input
21 type="number"
22 value={intervalValue}
23 onChange={handleChangeIntervalValue}
24 />
25 <button onClick={start}>start</button>
26 <button onClick={stop}>stop</button>
27 <button onClick={reset}>reset</button>
28 </div>
29 )
30}

Edit on CodeSandbox

See a way to make this page better?
Edit there »