Stopwatch Using ReactJS: 4 Easy Steps to Create Your First React Application
Stopwatch Using ReactJS: 4 Easy Steps
Learn the core concepts of React hooks like useState and useEffect by building a fully functional Stopwatch. The perfect "Hello World" project for your portfolio.
Building a Stopwatch is the ultimate rite of passage for new React developers. It seems simple on the surface, but it teaches you everything you need to know about component re-renders, state management, and side effects.
In this tutorial, we will strip away the complex jargon. In just 4 easy steps, you will create your first React application from scratch. Open your code editor, and let's get building.
4 Steps to Create Your Stopwatch
1. Setup the React Environment
We will use Vite because it is incredibly fast. Open your terminal and run the following command to generate your boilerplate code, then start your local development server.
npm create vite@latest stopwatch-app -- --template react
cd stopwatch-app
npm install
npm run dev
2. Define State with useState Hook
A stopwatch needs to track two things: the current time and whether it is running. We use the useState hook to store these values so React knows when to update the UI.
const [isRunning, setIsRunning] = useState(false);
3. The Timer Logic (useEffect Hook)
This is the brain of the app. We use useEffect to start a setInterval that adds 10 milliseconds to our time variable whenever isRunning is true. Don't forget to clear the interval to prevent memory leaks!
let intervalId;
if (isRunning) {
intervalId = setInterval(() => setTime(t => t + 1), 10);
}
return () => clearInterval(intervalId);
}, [isRunning]);
4. Build the UI & Buttons
Finally, we format the time into minutes, seconds, and milliseconds, and map our state functions to Start, Stop, and Reset buttons.
<div>
<h1>{formatTime(time)}</h1>
<button onClick={() => setIsRunning(!isRunning)}>
{isRunning ? 'Stop' : 'Start'}
</button>
<button onClick={() => { setIsRunning(false); setTime(0); }}>Reset</button>
</div>
What Did We Just Learn?
State (useState)
You learned how React stores data. When the state changes, React automatically re-renders the UI to show the new time.
Side Effects (useEffect)
You learned how to handle background tasks (like a running timer) without breaking or freezing the visual component.
Event Handling
You learned how to connect user clicks (onClick) to functions that update the logic of your application seamlessly.
Tech Stack Used
Ready to Master React?
Congratulations on completing your first React app! Take this code, style it with Tailwind, and deploy it to Vercel to show off your new skills.