How to create a Timer in React
Let’s see how you can create a simple timer in React. You’ll be needing useEffect
hook, setTimeout
and some HTML. Let’s try create a Timer React component.
Creating React Project
You can create a React project using create-react-app
npx create-react-app my-app
cd my-app
npm start
You will be able see the app running on http://localhost:3000/.
React Timer Component
Create a file called timer.js
inside the src
folder. Create a basic React component and initialize a variable for timer counter and a method to update the counter. Inside the useEffect
hook you can check for counter and until it’s not zero you can decrement the counter on each 1000ms using setTimeout
import { useEffect, useState } from "react";
function Timer({max}){
const [counter, setCounter] = useState(max);
useEffect(() =>{
if(counter > 0){
setTimeout(()=>setCounter(counter - 1), 1000);
}
},[counter]);
return(
<span>
{counter}
</span>
)
}
export default Timer;
You can use the Timer component inside the App.js
component after importing as shown:
<Timer max={60} />