Work with our skilled React developers to accelerate your project and boost its performance.
Hire Reactjs DevelopersCountdown timers are a common feature in modern web applications — used in quizzes, auctions, sales, product launches, and more. In this article, we’ll build a simple yet powerful countdown timer in React, without using any external libraries. Later, we’ll also look at a few popular libraries you can use if you want even faster or more feature-rich solutions.
Let’s dive straight into building a countdown timer using React hooks like useState and useEffect.
import React, { useState, useEffect } from 'react'; function CountdownTimer() { const [seconds, setSeconds] = useState(60); // Initial countdown time in seconds const [isActive, setIsActive] = useState(false); // To control start/pause useEffect(() => { if (!isActive || seconds === 0) return; const interval = setInterval(() => { setSeconds(prev => prev - 1); }, 1000); return () => clearInterval(interval); }, [isActive, seconds]); const startTimer = () => setIsActive(true); const secondsToTime = (secs) => { const hours = Math.floor(secs / 3600); const minutes = Math.floor((secs % 3600) / 60); const seconds = secs % 60; return { h: hours, m: minutes, s: seconds }; }; const { h, m, s } = secondsToTime(seconds); return ( <div> <h2>Countdown Timer</h2> <p>Time Remaining: {h} h : {m} m : {s} s</p> {!isActive && seconds > 0 && ( <button onClick={startTimer}>Start Timer</button> )} {seconds === 0 && <p>Time's up!</p>} </div> ); } export default CountdownTimer;
If you prefer not to reinvent the wheel, there are libraries that offer ready-to-use countdown components:
Install:
npm install react-countdown
Usage: import Countdown from 'react-countdown'; function Timer() { return (); }
Features:
Install:
npm install react-timer-hook
Usage:
import { useTimer } from 'react-timer-hook'; function MyTimer({ expiryTimestamp }) { const { seconds, minutes, hours, isRunning, start, pause, resume, restart, } = useTimer({ expiryTimestamp, onExpire: () => console.log('Timer expired') }); return (); }{hours}:{minutes}:{seconds}
Start, pause, resume, restart functionalities
Easy expiry handling
Building a countdown timer in React from scratch helps you understand how timers, effects, and states interact. For small projects or learning purposes, creating your own timer is a good practice. However, for production-grade apps where you need features like pause/resume/reset or custom rendering, using a library like react-countdown or react-timer-hook can save you time and reduce bugs.
Always remember to clear intervals properly inside useEffect to avoid performance issues or memory leaks, especially when working with timers!