In the previous blog, we explored the State and event handler. Now, In this tutorial, we will explore how to create a countdown timer using React.js. React.js is a popular JavaScript library for building user interfaces, and it provides a simple and efficient way to handle the state of our application.
Prerequisites
Before we start, make sure you have the following installed:
Node.js
npm (Node Package Manager)
Step 1: Setting Up the Project
Open your terminal and create a new directory for your project:
mkdir countdown-timer cd countdown-timer
Initialize a new React.js project:
npx create-react-app .
This command will set up a new React.js project in the current directory.
Start the development server:
npm start
This will start the development server, and you can see your React app running in your browser at
http://localhost:3000
.
Step 2: Creating the Countdown Component
Open the
src
directory and create a new file calledCountdown.js
. This is where we will define our countdown component.Open
Countdown.js
in your text editor and add the following code:import React, { useState, useEffect } from 'react'; const Countdown = () => { const [count, setCount] = useState(10); useEffect(() => { const countdown = setInterval(() => { setCount((prevCount) => prevCount - 1); }, 1000); return () => { clearInterval(countdown); }; }, []); return ( <div> <h1>Countdown Timer</h1> <p>{count}</p> </div> ); }; export default Countdown;
In this code, we are using the
useState
anduseEffect
hooks from React. Thecount
state variable holds the current count value, and thesetCount
function allows us to update it.The
useEffect
hook is responsible for starting and stopping the countdown. It runs once when the component is mounted, thanks to the empty dependency array ([]
). Inside theuseEffect
hook, we usesetInterval
to decrement the count by 1 every second. Finally, we clean up the interval in the cleanup function returned byuseEffect
to avoid memory leaks.Save the file.
Step 3: Using the Countdown Component
Open the
src
directory and edit theApp.js
file.Remove the existing code in
App.js
and replace it with the following:import React from 'react'; import Countdown from './Countdown'; const App = () => { return ( <div className="App"> <Countdown /> </div> ); }; export default App;
This code imports the
Countdown
component we created and renders it inside theApp
component.Save the file.
Go to your browser and you should see the countdown timer running!
Conclusion
In this tutorial, we learned how to create a countdown timer using React.js. We utilized React's useState
and useEffect
hooks to manage the state of our application and update the count value every second. React's component-based architecture made it easy to create reusable and modular code. Feel free to customize the countdown timer further or add additional features to suit your needs. Happy coding!