DEV Community

Cover image for Building a Stopwatch in React
Kartik Budhraja
Kartik Budhraja

Posted on

Building a Stopwatch in React

In this article, we will walk through the process of creating a stopwatch application using React. We will break down the code step by step, explaining each part of the implementation. By the end of this article, you will have a clear understanding of how to build a functional stopwatch in React.

Follow - Linkedin

Setting Up the Initial State:

We begin by initializing the state variables timer and isRunning using the useState hook. timer keeps track of the elapsed time, and isRunning determines whether the stopwatch is actively running.

const [timer, setTimer] = useState(0);
const [isRunning, setIsRunning] = useState(false);
Enter fullscreen mode Exit fullscreen mode

Handling Start, Pause, and Reset:

These functions control the behavior of the stopwatch. handleStart starts the timer by incrementing the timer state every 10 milliseconds. handlePause stops the timer, and handleReset resets both the timer and the running interval.

const handleStart = () => {
  if (isRunning) return;
  setIsRunning(true);
  timeInterval.current = setInterval(() => {
    setTimer((prev) => prev + 1);
  }, 10);
};

const handlePause = () => {
  if (!isRunning) return;
  setIsRunning(false);
  clearInterval(timeInterval.current);
};

const handleReset = () => {
  setIsRunning(false);
  clearInterval(timeInterval.current);
  setTimer(0);
};
Enter fullscreen mode Exit fullscreen mode

Formatting the Timer:

The formatTime function takes the raw timer value (in milliseconds) and formats it into minutes, seconds, and milliseconds. The padStart method ensures that the formatted values always have two digits for minutes and seconds and three digits for milliseconds.

const formatTime = (timer) => {
  const minutes = Math.floor(timer / 60000).toString().padStart(2, "0");
  const seconds = Math.floor((timer / 1000) % 60).toString().padStart(2, "0");
  const milliseconds = (timer % 1000).toString().padStart(3, "0");

  return { minutes, seconds, milliseconds };
};

const { minutes, seconds, milliseconds } = formatTime(timer);
Enter fullscreen mode Exit fullscreen mode

Displaying the Timer:

Here, we use the timer-box class to style each unit of time (minutes, seconds, and milliseconds). The colons are added as separate span elements with a colon class for styling.

<div className="timer-container">
  <div className="timer-box">
    <h1>{minutes}</h1>
  </div>
  <span className="colon">:</span>
  <div className="timer-box">
    <h1>{seconds}</h1>
  </div>
  <span className="colon">:</span>
  <div className="timer-box">
    <h1>{milliseconds}</h1>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Managing the Interval with useRef:

We utilize the useRef hook to maintain a reference to the interval ID. This reference allows us to clear the interval when the timer is paused or reset, preventing memory leaks.

let timeInterval = useRef(null);
Enter fullscreen mode Exit fullscreen mode

Here is the reference of the working code


Conclusion:

By following these steps, you've successfully created a functional stopwatch in React. Understanding the logic behind each part of the code is crucial for building more complex applications. Happy coding!

Follow Me on Social Media!
If you found this article helpful, feel free to connect with me on LinkedIn for more programming tips and tutorials. Let's learn and grow together!

LinkedIn: https://www.linkedin.com/in/kartikbudhraja/

Top comments (0)