How to create a countdown timer in React JS using React hooks useState & useEffect
In this article, we will learn how to create a countdown timer in React JS using React hooks useState and useEffect.
We will be using the useState hook to manage the state of our countdown timer and the useEffect hook to update the timer every second.
First, let’s create a new React project and install the necessary packages:
npx create-react-app countdown-timer
cd countdown-timer
Now, let’s create a new file named Timer.js inside the src folder. We will write the logic for our countdown timer inside this file.
import React, { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(60);
useEffect(() => {
const interval = setInterval(() => {
setCount(count - 1);
}, 1000);
return () => clearInterval(interval);
}, [count]);
return (
Countdown Timer: {count}
);
}
export default Timer;
In the code above, we first import the useState and useEffect hooks from the ‘react’ package. We then declare a count state variable using the useState hook and initialize it to 60, which is the starting value for our countdown timer.
Inside the useEffect hook, we set up an interval that updates the count state variable every second. We also return a cleanup function that clears the interval when the component is unmounted.
Now, let’s use our Timer component in the App.js file:
import React from 'react';
import Timer from './Timer';
function App() {
return (
Countdown Timer App
);
}
export default App;
That’s it! We have created a countdown timer in React JS using useState and useEffect hooks. Now, when you run the project using ‘npm start’, you will see the countdown timer ticking down from 60 to 0.
Congratulations! You have successfully created a countdown timer in React JS using React hooks useState and useEffect.
Sir, Your style of explaining is unique, explain very nicely.please – React E-Commerce project build up
Time to code . What are your plans for 2023?