codedamn logo
codedamn

Countdown timer in ReactJs- full guide to it

  • Vishnupriya's profile image
    Vishnupriya
    Team codedamn
Countdown timer in ReactJs- full guide to it

Hey readers, in this article we will be learning about how to make a countdown timer in ReactJs. If you’re new to React, do check out React article or course on Codedamn and check out the YouTube channel

React is an open-source, JavaScript library used for building UI and components in the front-end of an application. It is developed by Meta (previously Facebook). 

It is widely used for building large-scale complex applications because of the concept of reusable components, state, props, hooks, redux, and simple design. It helps us to render HTML code snippets used for building web apps. 

For instance, on Instagram, whenever you upload an image, you get likes and comments. These likes and comments are nothing but React components. React checks the state of the component and renders only that component that is changed. This is just a glimpse of how React works at the front-end. The same is applied to the countdown timer where it is getting updated every second and the component has to render itself. Now that we know the basics, let’s understand what is a countdown timer and how it can be implemented using React.

What is a countdown timer?

It is a timer that shows the beginning and end of an event. This event can be anything like a birthday or sale. It is extensively used by applications where upcoming sales have to be displayed like Flipkart, Amazon, etc.

Approach for making countdown timer in React

  • getTimeRemaming– It computes the difference between the current time and the target timer. It basically checks the time left from the target timer and current by doing calculations and returns the output as a total number of hours, minutes, and seconds in the application.
  • StartTime– This function will execute the function and will start timing down the total number of hours, minutes, and the second in the application.
  • ClearTimer– It is used for resetting the timer function. If the timer is restarted, it clears the remaining time from the previous countdown. Other than this, it can also start the parallel two-timing down or collapse everything.
  • getDeadTimer– In this, the deadline of the timer is provided from the starting point of time. In order to extend the time, add it to the application.

Steps for creating countdown timer in React js

  1. Create React application using the following command:
    npx create-react-app codedamn
  2. Go to the folder created: cd codedamn.
  3. Create a file App.js if it doesn’t exist in the folder and write the following code.
import React, { useState, useRef, useEffect } from 'react'
const App = () => {
const Ref = useRef(null);
const [timer, setTimer] = useState('00:00:00');
const getTimeRemaining = (e) => {
const total = Date.parse(e) - Date.parse(new Date());
const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor((total / 1000 / 60) % 60);
const hours = Math.floor((total / 1000 * 60 * 60) % 24);
return {
total, hours, minutes, seconds
};
}
const startTimer = (e) => {
let { total, hours, minutes, seconds }
= getTimeRemaining(e);
if (total >= 0) {
setTimer(
(hours > 9 ? hours : '0' + hours) + ':' +
(minutes > 9 ? minutes : '0' + minutes) + ':'
+ (seconds > 9 ? seconds : '0' + seconds)
)
}
}
const clearTimer = (e) => {
if (Ref.current) clearInterval(Ref.current);
const id = setInterval(() => {
startTimer(e);
}, 1000)
Ref.current = id;
}
const getDeadTime = () => {
let deadline = new Date();
deadline.setSeconds(deadline.getSeconds() + 10);
return deadline;
}
useEffect(() => {
clearTimer(getDeadTime());
}, []);
const onClickReset = () => {
clearTimer(getDeadTime());
}
return (
<div className="Codedamn App">
<h2>{timer}</h2>
<button onClick={onClickReset}>Reset</button>
</div>
)
}
export default App

Explanation of the countdown timer code

Ref is used because we are dealing with setInterval of JavaScript to keep track and to stop it when needed. The state of the timer is initialized and the calculations for the timer are done. The timer function gets executed when the button is clicked and it updates it when it is less than 10 and then it adds 0 in the beginning.

We can use useEffect so that when the component mounts, the timer will start as soon as possible. We put an empty array to act as componentDidmount only. The way to call the clearTimer() to start the countdown is via action event from the button first; we create a function to be called by the button within an application. This is how the application functions internally. 

Conclusion

This is how the countdown timer is made in React, if you want to learn more about React, do check out the article and course on Codedamn of React. Hope you liked this, if you have any queries or suggestions do let us know in the comments. 

If you are interested in learning React, do check out Courses on Codedamn with an in-built environment playground to learn and practice code. Join the Community of Codedamn and do check out other articles related to programming and development on Codedamn and subscribe to our newsletter to never miss out on our new programs and updates.

If you have any queries or feedback do let us know in the comment section. Also, if you sign up on the Codedamn, then do check out the referral section, copy your link and refer to as many people as possible, and get exciting gifts, swags, and prizes from Codedamn. So, don’t forget to check that out!

User avatar