Easy Tutorial to Create a StopWatch in React

Easy Tutorial to Create a StopWatch in React

React is a popular JavaScript library for building user interfaces, and one of its many advantages is its ability to create interactive and dynamic components. In this tutorial, we will walk you through the step-by-step process of creating a stopwatch in React. Whether a beginner or an experienced developer, this tutorial will provide you with the knowledge and skills to create your stopwatch application using React. So, let’s get started and create a functional and visually appealing stopwatch in React!

Setting up the project

To keep the tutorial simple and short, I won’t be using any extra libraries for designing or functionality. We will create two main elements in our UI, one is displaying the stopwatch’s current value and a button to drive the stopwatch.

In our button containers, we would be having three buttons, Start, Pause, and Reset

  • Start Button  – will start the stopwatch countdown.
  • Pause Button  – will pause the stopwatch countdown.
  • Reset Button  – will reset/default the stopwatch countdown.

Initially, our StopWatch code and UI will look something Like this, 

StopWatch Tutorial in React

Also read, How to add/remove input fields dynamically with Reactjs

Adding Functionality

The primary function that will update our stopwatch at every second is the setInterval and useEffect function. First, we will add three (seconds, minutes, hours) useState hooks for tracking seconds, minutes, and hours and populate them into render view.

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [seconds, setSeconds] = useState(0);
  const [minutes, setMinutes] = useState(0);
  const [hours, setHours] = useState(0);
  
  return (
    <div className="App">
      <h1>StopWatch</h1>
      <h2>{`${hours}:${minutes}:${seconds}`}</h2>
      <div className="container">
        <button className="start-btn">
          Start
        </button>
        <button className="pause-btn">
          Pause
        </button>
        <button className="reset-btn">
          Reset
        </button>
      </div>
    </div>
  );
}

Now we will create three functions that will get triggered when respective buttons are clicked. We will also create one more boolean (running) useState hook which will help us to achieve pause functionality in our stopWatch.

Also read, It’s the End of Computer Programming as We Know It. (And I Feel Fine.)

When you click on the Start button, the start function gets triggered, and It updates our hook, isRunning to true. This signals the stopwatch to start running which I will explain in detail about the logic down the tutorial. 

When you click on the Pause button, the pause function gets triggered, and It updates our hook, isRunning to false. This signals the stopwatch to pause/stop running.

When you click on the Reset button, the reset function gets triggered, and It updates our hook, isRunning to false, and rests our seconds, minutes, and hours hooks to default 0.

Also read, Easy tutorial to build React Autosuggest from scratch

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [seconds, setSeconds] = useState(0);
  const [minutes, setMinutes] = useState(0);
  const [hours, setHours] = useState(0);
  const [running, setRunning] = useState(false);

  const start = () => {
    setRunning(true);
  };

  const pause = () => {
    setRunning(false);
  };

  const reset = () => {
    setRunning(false);
    setSeconds(0);
    setMinutes(0);
    setHours(0);
  };

  return (
    <div className="App">
      <h1>StopWatch</h1>
      <h2>{`${hours}:${minutes}:${seconds}`}</h2>
      <div className="container">
        <button className="start-btn" onClick={start}>
          Start
        </button>
        <button className="pause-btn" onClick={pause}>
          Pause
        </button>
        <button className="reset-btn" onClick={reset}>
          Reset
        </button>
      </div>
    </div>
  );
}

Now comes the most important part of our tutorial, setting up useEffect which will update our StopWatch. The useEffect hook allows you to perform side effects in functional components. In this case, the code is setting up a timer to update the state values of seconds, minutes, and hours at regular intervals.

Also read, Simple tutorial on React authentication with redux + Example

useEffect(() => {
    let interval = null;
    if (running) {
      interval = setInterval(() => {
        setSeconds(seconds + 1);
        if (seconds === 60) {
          setMinutes(minutes + 1);
          setSeconds(0);
        }
        if (minutes === 60) {
          setHours(hours + 1);
          setMinutes(0);
        }
      }, 1000);
    }

    return () => {
      clearInterval(interval);
    };
}, [running, hours, minutes, seconds]);

Here’s a breakdown of what the code does:

  • When the component mounts or when the running variable changes, the useEffect function is called.
  • Inside the useEffect function, a variable called interval is declared and initialized to null.
  • If the value of running is true, a new interval is created using the setInterval function. This interval runs a callback function every 1000 milliseconds (1 second).
  • Inside the callback function, the setSeconds function is called to update the seconds state by incrementing it by 1.
  • If the value of seconds becomes equal to 60, the setMinutes function is called to update the minutes state by incrementing it by 1, and the seconds state is reset to 0.
  • Similarly, if the value of minutes becomes equal to 60, the setHours function is called to update the hours state by incrementing it by 1, and the minutes state is reset to 0.
  • Finally, the useEffect function returns a cleanup function that clears the interval using the clearInterval function. This cleanup function is called when the component unmounts or when the running variable changes.

Thus when you click on the start button our stopwatch starts running!

Also read, Build your own OTP verification UI using React, Formik & TypeScript

Last Words

In conclusion, creating a stopwatch in React can be a straightforward process with the right tutorial. This article provided a step-by-step guide that makes it easy for beginners to understand and follow along. If you found this tutorial helpful, please share it with others who may also benefit from it. Additionally, feel free to explore our website for more informative and helpful articles on React development and other related topics.

Table of Contents