How to Build a Simple React Stopwatch Timer

Project Setup

  1. Prerequisites: Ensure you have Node.js and npm (or yarn) installed on your system.

  2. Create React App:

    Bash
    npx create-react-app my-stopwatch-app
    cd my-stopwatch-app
    

Component Structure

  1. Create a Component: Inside your src folder, create a file named Stopwatch.jsx. This will contain the logic and structure of your stopwatch.

Basic Stopwatch Implementation

JavaScript
import React, { useState, useEffect, useRef } from 'react';

function Stopwatch() {
  const [timer, setTimer] = useState(0);
  const [isRunning, setIsRunning] = useState(false);
  const intervalRef = useRef(null);

  useEffect(() => {
    if (isRunning) {
      intervalRef.current = setInterval(() => {
        setTimer((prevTimer) => prevTimer + 10);
      }, 10);
    } else if (!isRunning) {
      clearInterval(intervalRef.current);
    }

    return () => clearInterval(intervalRef.current);
  }, [isRunning]);

  const startTimer = () => {
    setIsRunning(true);
  };

  const stopTimer = () => {
    setIsRunning(false);
  };

  const resetTimer = () => {
    setTimer(0);
  };

  const formatTime = (timer) => {
    const getSeconds = `0${(timer / 1000) % 60}`.slice(-2);
    const minutes = `${Math.floor(timer / 60000)}`.padStart(2, '0');
    const milliseconds = `0${(timer % 1000)}`.slice(-3);

    return `${minutes} : ${getSeconds} : ${milliseconds}`;
  };

  return (
    <div className="stopwatch">
      <h2>Stopwatch</h2>
      <div className="stopwatch-display">
        {formatTime(timer)}
      </div>
      <div className="stopwatch-buttons">
        <button onClick={startTimer}>Start</button>
        <button onClick={stopTimer}>Stop</button>
        <button onClick={resetTimer}>Reset</button>
      </div>
    </div>
  );
}

export default Stopwatch;

Explanation

  • State:
    • timer: Stores the elapsed time in milliseconds.
    • isRunning: Indicates if the stopwatch is running.
  • useRef:
    • intervalRef stores the interval ID, allowing us to clear the interval when needed.
  • useEffect:
    • Manages the interval for updating the timer when isRunning changes.
    • The cleanup function clears the interval when the component unmounts or isRunning becomes false.
  • Functions:
    • startTimer: Sets isRunning to true to start the timer.
    • stopTimer: Sets isRunning to false to stop the timer.
    • resetTimer: Resets the timer state to 0.
  • formatTime: Helper function to format the time display.

Rendering the Stopwatch

In your main App.js file:

JavaScript
import React from 'react';
import Stopwatch from './Stopwatch';

function App() {
  return (
    <div className="App">
      <Stopwatch />
    </div>
  );
}

export default App;

Styling

Add some CSS in a Stopwatch.css file (and import it into your Stopwatch.jsx):

CSS
/* Stopwatch.css */
.stopwatch { /* ... */ }
.stopwatch-display { /* ... */ }
.stopwatch-buttons { /* ... */ }

Start the App:

Bash
npm start