How to Create Custom Stopwatch Component 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.

A stopwatch is a hardware or software device used to calculate the time elapsed from a specific point in time.

A stopwatch contains several buttons allowing user to operate it based on their goals. It typically has a start, stop and reset stopwatch button.

In general, stopwatches are used in various events where participants’ performance is time-based.

Apart from that, it is also used for timing tasks in scientific experiments, cooking, and other applications where accurate timing is important.

React Bootstrap Custom Stop Watch Component Example

  • Step 1: Define New React Project
  • Step 2: Install Bootstrap UI
  • Step 3: Create Function File
  • Step 4: Build Stop Watch Module
  • Step 5: Add Module to Main Entry
  • Step 6: Start Development Server

Define New 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

Install Bootstrap UI

Bootstrap makes it easy to build modern and responsive web applications quickly and efficiently through its large set of readymade UI components.

It can be installed using a single command…

npm install bootstrap --legacy-peer-deps

Build Stop Watch Module

Our stopwatch component has two child component one manages the timer another manages the timer. There we need to create three components.

To demystify the stop watch module building process we have to paste all of the given code into the components/StopWatch.js file.

import React, { useState, useEffect } from "react";
import Watch from "./Watch";
import Controls from "./Controls";
function StopWatch() {
  const [active, setActive] = useState(false);
  const [pause, setPause] = useState(true);
  const [duration, setDuration] = useState(0);
  useEffect(() => {
    let timePeriod = null;
    if (active && pause === false) {
      timePeriod = setInterval(() => {
        setDuration((duration) => duration + 10);
      }, 10);
    } else {
      clearInterval(timePeriod);
    }
    return () => {
      clearInterval(timePeriod);
    };
  }, [active, pause]);
  const initWatch = () => {
    setActive(true);
    setPause(false);
  };
  const initResume = () => {
    setPause(!pause);
  };
  const initReset = () => {
    setActive(false);
    setDuration(0);
  };
  return (
    <div className="stop-watch">
      <Watch time={duration} />
      <Controls
        initWatch={initWatch}
        initResume={initResume}
        initReset={initReset}
        active={active}
        pause={pause}
      />
    </div>
  );
}
export default StopWatch;

Make the components/stopwatch/Controls.js file and to formulate the stopwatch controls add the code to the file.

import React from "react";
function Controls(prop) {
  const invokeTimer = (
    <div className="d-grid gap-2 mt-3">
      <div className="btn btn-danger" onClick={prop.initWatch}>
        Start
      </div>
    </div>
  );
  const activeTimer = (
    <div className="d-grid gap-2 mt-3">
      <div className="btn btn-danger" onClick={prop.initReset}>
        Reset
      </div>
      <div className="btn btn-success" onClick={prop.initResume}>
        {prop.paused ? "Resume" : "Pause"}
      </div>
    </div>
  );
  return (
    <div>
      <div>{prop.active ? activeTimer : invokeTimer}</div>
    </div>
  );
}
export default Controls;

In this step you need to make the components/stopwatch/Watch.js file and add the code in the file. This file will decide how your watch look.

import React from "react";
function Watch(t) {
  return (
    <h2 className="display-1">
      <span>{("0" + Math.floor((t.time / 60000) % 60)).slice(-2)}:</span>
      <span>{("0" + Math.floor((t.time / 1000) % 60)).slice(-2)}.</span>
      <span>{("0" + ((t.time / 10) % 100)).slice(-2)}</span>
    </h2>
  );
}
export default Watch;

Add Module to Main Entry

We will now look for the App.js file that you can easily locate in src/ folder. Here you have to import the StopWatch module into the file.

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import StopWatch from "./components/stopwatch/StopWatch";
function App() {
  return (
    <div className="container mt-4">
      <h2 className="mb-3">React Bootstrap Stop Watch Example</h2>
      <div className="card">
        <div className="card-body text-center">
          <StopWatch />
        </div>
      </div>
    </div>
  );
}
export default App;

Start Development Server

We are going to test and checkout what we have achieved so far therefore run the given command.

npm start

Your react development server will serve the test app on the given url:

http://localhost:3000

How to Create Custom Stopwatch Component in React

Conclusion

In this short descriptive guide, we learned how to quickly and systematically build a small yet user-friendly stopwatch component using the React framework and the core React hook.

I hope this little tutorial will help you understand how things are developed in React realm.

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.