How to Create Custom Countdown Timer Clock in React 18

Last Updated on by in React JS

In this comprehensive guide, i will tell you how to build a simple custom countdown timer component using React js framework.

To build the countdown component in React we will use React hooks (useState, useEffect, useRef) and bootstrap.

React Hooks are a feature introduced in React version 16.8 that allows developers to use state and other React features in functional components without converting them into class components.

Hooks are functions that let you “hook into” React state and lifecycle features from functional components.

Some commonly used React Hooks are:

useState: This hook lets you add state to functional components. It returns an array containing the current state and a function to update that state.

useEffect: This hook lets you perform side effects in functional components. You can use it to fetch data, subscribe to events, and perform other side effects.

useRef: is a built-in hook in React that provides a way to create a mutable reference to a value that persists across re-renders.

A countdown timer is a tool that counts down the time remaining until a particular event or deadline. It is commonly used to track the time remaining until an event.

Countdown timers can be physical devices or software applications, and they are commonly used in a variety of settings, including homes, schools, and workplaces.

React Bootstrap Custom Countdown Timer Component Example

  • Step 1: Install React Project
  • Step 2: Add Bootstrap UI
  • Step 3: Create Function Component
  • Step 4: Build Countdown Timer Component
  • Step 5: Update Main Entry Point
  • Step 6: Evoke Development Server

Install React Project

The first step begins by installing a brand-new React framework. It is easy to download a fresh copy of React project on your system.

Ensure you have node and npm configured on your device before executing the given command.

npx create-react-app my-react-app
cd my-react-app

Add Bootstrap UI

You are into your app, open the terminal type the command and hit enter to add bootstrap library in your React project.

npm install bootstrap --legacy-peer-deps

Create Function Component

A function component is a normal JavaScript function that holds the code to solve a particular problem.

Next, you have to create the components folder and then a Countdown.js file.

import React from 'react'

function Countdown() {
  return (
    <div></div>
  )
}

export default Countdown

Build Countdown Timer Component

Open the components/Countdown.js file in code editor and make sure to insert all the given code into the component file.

import React, { useState, useEffect, useRef } from "react";

function Countdown() {
  let refInstance = useRef(null);

  let [counter, setCountdown] = useState("00:00:00");

  let getCounter = (e) => {
    let all = Date.parse(e) - Date.parse(new Date());
    let s = Math.floor((all / 1000) % 60);
    let m = Math.floor((all / 1000 / 60) % 60);
    let h = Math.floor((all / 1000 / 60 / 60) % 24);
    return {
      all,
      s,
      m,
      h,
    };
  };

  let initCounter = (e) => {
    let { all, h, m, s } = getCounter(e);
    if (all >= 0) {
      setCountdown(
        (h > 9 ? h : "0" + h) +
          ":" +
          (m > 9 ? m : "0" + m) +
          ":" +
          (s > 9 ? s : "0" + s),
      );
    }
  };

  let reset = (e) => {
    setCountdown("00:00:20");
    if (refInstance.current) clearInterval(refInstance.current);
    let id = setInterval(() => {
      initCounter(e);
    }, 1000);
    refInstance.current = id;
  };

  let voidTime = () => {
    let voidZone = new Date();
    voidZone.setSeconds(voidZone.getSeconds() + 20);
    return voidZone;
  };

  useEffect(() => {
    reset(voidTime());
  }, []);

  let onReset = () => {
    reset(voidTime());
  };

  return (
    <>
      <h1 className="h1 alert alert-info text-center">{counter}</h1>
      <div className="d-grid">
        <button className="btn btn-dark" onClick={onReset}>
          Reset
        </button>
      </div>
    </>
  );
}

export default Countdown;

Update Main Entry Point

In React, the app.js file is the main entry point for the application’s JavaScript code.

This file holds the initial configuration and setup for the React application.

In order to execute the programme that we have built needs to be inserted in the src/App.js file.

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Countdown from "./components/Countdown.js";

function App() {
  return (
    <div>
      <h2 className="mb-3">React Countdown Timer Clock Example</h2>
      <Countdown />
    </div>
  );
}

export default App;

Evoke Development Server

In React, a development server is a tool that helps front-end developers test and runs their applications locally during development.

It provides a facile way to view changes made to the code and check for any potential issues before deploying the application to a live server.

Invoke the server using the given command:

npm start

On your terminal window, you will see urls that you can use on the browser to check the app.

http://localhost:3000

How to Create Custom Countdown Timer Clock in React

Conclusion

In this post, we have profoundly discussed building a custom countdown timer clock using the core React hooks.

Hooks are functions that let you “hook into” React state and lifecycle features from functional components.

We hope this tutorial will help you learn how to efficiently build useful features in React environment without using any external library.