Building a Simple Stopwatch in React: A Step-By-Step Guide
Stopwatches are handy tools for measuring time precisely. In this tutorial, we’ll walk through the process of creating a simple stopwatch using React. By the end of this guide, you’ll have a functional stopwatch component that you can integrate into your React applications. This is also an important interview question for senior javascript developers
Prerequisites
Before we dive into building our stopwatch, make sure you have the following:
- Node.js is installed on your machine.
- A basic understanding of React concepts.
- Optionally, a new React app set up using
create-react-app. If not, you can create one by running the following commands:
npx create-react-app react-stopwatch
cd react-stopwatchSetting Up the Stopwatch Component
Now, open the src/App.js file, and replace its content with the following code:
import React from 'react'
import './styles.css'
export function App() {
const [currentState, setCurrentState] = React.useState('')
const [currentTime, setCurrentTime] = React.useState(0)
const intervalRef = React.useRef()
const onStart = () => {
if (currentState === 'START') return
setCurrentState('START')
intervalRef.current = setInterval(() => {
setCurrentTime((currentTime) => currentTime + 50)
}, 50)
}
const onStop = () => {
if (currentState === 'STOP') return
setCurrentState('STOP')
clearInterval(intervalRef.current)
}
const onReset = () => {
if (currentState === 'RESET') return
setCurrentTime(0)
}
const sec = Math.floor(currentTime / 1000)
const min = Math.floor(sec / 60)
const hour = Math.floor(min / 60)
const millis = (currentTime % 1000).toString().padStart(3,"0")
const seconds = (sec % 60).toString().padStart(2,"0")
const minutes = (min % 60).toString().padStart(2,"0")
const hours = (hour % 24).toString().padStart(2,"0")
return (
<div className="App">
<button onClick={onStart}>Start</button>
<button onClick={onStop}>Stop</button>
<button onClick={onReset}>Reset</button>
<div className="timer">
<span>{hours}</span>:<span>{minutes}</span>:<span>{seconds}</span>:
<span>{milli}</span>
</div>
</div>
)
}Styling the Stopwatch
Next, let’s add some basic styles to make our stopwatch visually appealing. Create a new file named style.css in the src folder and add the following styles:
.App {
text-align: center;
padding: 50px;
}
button {
font-size: 18px;
margin: 0 10px;
padding: 10px 20px;
cursor: pointer;
}
.timer {
font-size: 24px;
margin-top: 20px;
padding: 10px;
background-color: #f0f0f0;
border-radius: 5px;
display: inline-block;
}Get Deepanshu Shukla’s stories in your inbox
Join Medium for free to get updates from this writer.
Understanding the Code
Let’s break down the key parts of our stopwatch component:
State Variables
We use the useState hook to manage the current state (currentState) and the elapsed time (currentTime).
const [currentState, setCurrentState] = React.useState('');
const [currentTime, setCurrentTime] = React.useState(0);
const intervalRef = React.useRef();Button Click Handlers
The onStart, onStop, and onReset functions handle the logic for starting, stopping, and resetting the stopwatch, respectively.
const onStart = () => {
// Check if the stopwatch is already in the "START" state
if (currentState === 'START') return;
setCurrentState('START');
intervalRef.current = setInterval(() => {
setCurrentTime((currentTime) => currentTime + 50);
}, 50);
};
const onStop = () => {
// Check if the stopwatch is already in the "STOP" state
if (currentState === 'STOP') return;
setCurrentState('STOP');
clearInterval(intervalRef.current);
};
const onReset = () => {
// Check if the stopwatch is already in the "RESET" state
if (currentState === 'RESET') return;
setCurrentState('RESET');
setCurrentTime(0);
clearInterval(intervalRef.current);
};Time Formatting
We calculate the hours, minutes, seconds, and milliseconds based on the elapsed time.
const sec = Math.floor(currentTime / 1000)
const min = Math.floor(sec / 60)
const hour = Math.floor(min / 60)
const millis = (currentTime % 1000).toString().padStart(3,"0")
const seconds = (sec % 60).toString().padStart(2,"0")
const minutes = (min % 60).toString().padStart(2,"0")
const hours = (hour % 24).toString().padStart(2,"0")Testing the Stopwatch
Now, run your React app and test the stopwatch functionality. Click the “Start,” “Stop,” and “Reset” buttons to see the timer in action.
Congratulations! You’ve successfully built a simple stopwatch component in React. Feel free to enhance and customize it further based on your project’s needs.





