Categories
React Projects

Create a Stopwatch App with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a stopwatch app with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app stopwatch

with NPM to create our React project.

Also, we have to install the moment library to make calculating and formatting the duration easier.

To install it, we run:

npm i moment

Create the Stopwatch App

To create the stopwatch, we write:

import React, { useState } from "react";
import moment from "moment";

export default function App() {
  const [startDate, setStartDate] = useState(new Date());
  const [diff, setDiff] = useState("00:00:00");
  const [timer, setTimer] = useState();

  return (
    <div className="App">
      <button
        onClick={() => {
          setStartDate(new Date());
          const timer = setInterval(() => {
            let start = moment(startDate);
            let end = moment(new Date());
            let diff = end.diff(start);
            let f = moment.utc(diff).format("HH:mm:ss.SSS");
            setDiff(f);
          }, 1000);
          setTimer(timer);
        }}
      >
        start
      </button>
      <button onClick={() => clearInterval(timer)}>stop</button>
      <p>{diff}</p>
    </div>
  );
}

We have the startDate state to store the start date time.

diff stores the elapsed time as a string.

timer has the timer object.

Then we add a button with a function that calls setStartDate to set the start date.

Then we create a timer that runs every second with setInterval .

In the setInterval callback, we create moment objects from the startDate and the current date-time.

We call moment to create those objects.

Then we get the elapsed time between them with the diff method.

And then we get the elapsed time formatted into a string with the moment.utc method and the format method.

Also, we call setTimer to set the timer state to our setIntervaltimer.

Next, we have the stop button to call clearInterval to stop the timer.

And the p element displays the formatted elapsed time string.

Conclusion

We can create a stopwatch easily with React and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *