Skip to main content

useCountDown

Start, pause, resume, and reset a countdown timer.


API​

const [timeLeft, actions] = useCountDown({
defaultDuration,
interval,
startOnMount,
});

Options​

  • defaultDuration?: number
    • Defaults to 60000 (60 seconds)
    • Default duration in milliseconds
  • interval?: number
    • Defaults to 10000 (1 second)
    • Countdown interval in milliseconds
  • startOnMount?: boolean
    • Defaults to false
    • Determine whether the countdown should start on mount

Returns​

  • timeLeft: number
    • Timeleft in milliseconds
  • actions

    • actions.start: (duration?: number) => void
      • Function to start the countdown timer
      • You can customize the countdown timer duration in this function
    • actions.pause: () => void
      • Function to pause the countdown timer
    • actions.resume: () => void
      • Function to resume the paused countdown timer
    • actions.reset: () => void
      • Function to reset the countdown timer, this will set the timerleft to its default duration
    • actions.stop: () => void
      • Function to stop the countdown timer, this will set the timerleft to 0

Examples​

Countdown Timer​

http://localhost:3000/
10.00
import { useCountDown } from 'react-power-ups';

export function DemoTimer() {
const [timeLeft, actions] = useCountDown({ defaultDuration: 10_000, interval: 100 });

return (
<>
<div>{(timeLeft / 1000).toFixed(2)}</div>

<button onClick={() => actions.start()}>Start</button>
<button onClick={() => actions.start(4_200)}>Start for 4.2s</button>
<button onClick={() => actions.pause()}>Pause</button>
<button onClick={() => actions.resume()}>Resume</button>
<button onClick={() => actions.reset()}>Reset</button>
<button onClick={() => actions.stop()}>Stop</button>
</>
);
}

Sending OTP Timer​

http://localhost:3000/

OTP sent, check your phone!

Resend OTP in 10s
import { useCountDown } from 'react-power-ups';

export function DemoOTP() {
const [timeLeft, { start }] = useCountDown({ defaultDuration: 10_000, startOnMount: true });

const sendOTP = () => {
console.info('Resending OTP...');
start();
};

return (
<>
<p>OTP sent, check your phone!</p>

<button onClick={sendOTP} disabled={timeLeft > 0}>
{timeLeft ? '🚫' : '🟢'} Send OTP
</button>

{timeLeft > 0 && <span> Resend OTP in {timeLeft / 1000}s</span>}
</>
);
}

Code: https://github.com/afiiif/react-power-ups/blob/main/src/use-count-down.ts