Countdown Timer

A custom hook to manage a countdown timer (cool down) in seconds.

use-cool-down.tsx

tsx
1import { useCallback, useEffect, useState } from "react"; 2 3interface UseCoolDownResult { 4 coolDown: number; 5 startCoolDown: (duration: number) => void; 6} 7 8/** 9 * @description A custom hook to manage a countdown timer (cool down) in seconds. 10 * @param initialCoolDown Initial cool down duration in seconds. 11 * @returns An object containing the current cool down time and a function to start the cool down. 12 */ 13export function useCoolDown(initialCoolDown: number = 0): UseCoolDownResult { 14 const [coolDown, setCoolDown] = useState<number>(initialCoolDown); 15 16 const startCoolDown = useCallback((duration: number): void => { 17 setCoolDown(Math.max(0, duration)); 18 }, []); 19 20 useEffect(() => { 21 let interval: NodeJS.Timeout | undefined; 22 if (coolDown > 0) { 23 interval = setInterval(() => { 24 setCoolDown((prev) => Math.max(0, prev - 1)); 25 }, 1000); 26 } 27 return () => { 28 if (interval) clearInterval(interval); 29 }; 30 }, [coolDown]); 31 32 return { coolDown, startCoolDown }; 33}

Usage

tsx
1import { useCoolDown } from "@/hooks/use-cool-down"; 2 3export default function VerifyOtp() { 4 const { coolDown, startCoolDown } = useCoolDown(60); 5 6 return ( 7 <Button onClick={() => startCoolDown(60)} disabled={coolDown > 0}> 8 {coolDown > 0 ? `Resend OTP in ${coolDown}s` : "Resend OTP"} 9 </Button> 10 ); 11}

Loved this post?

Comments

Interested in
working
with me?

Let's Connect

Stay in touch 👇

© 2021 - 2025 itsrakesh. v2.