React.js Interview Question: Design a Stopwatch

React.js Interview Question: Design a Stopwatch

In many React.js interviews, candidates are often asked to demonstrate their understanding of React concepts by building a small application. In this blog post, we'll tackle a common interview question: "Design a Stopwatch in React." We'll walk through the process of building a simple stopwatch using React functional components and hooks. By the end of this tutorial, you'll have a fully functional stopwatch component that you can showcase in your React.js interviews.

Getting Started

Before we dive into the code, let's briefly outline the key functionalities we want our stopwatch to have:

  1. Start: Start the stopwatch timer.

  2. Pause: Pause the running stopwatch.

  3. Reset: Reset the stopwatch to zero.

Now, let's start building our stopwatch component step by step.

Step 1: Setting Up the Project

Assuming you have Node.js and npm installed, create a new React app using the following command:

npx create-react-app react-stopwatch
cd react-stopwatch

Now, let's create a new functional component for our stopwatch.

Step 2: Building the Stopwatch Component

In the src folder, create a new file called Stopwatch.js and implement the stopwatch component. We'll use React hooks like useState, useEffect, and useRef to manage state and handle side effects.

// Import necessary dependencies
import React, { useState, useEffect, useRef } from 'react';

const Stopwatch = () => {
  // State for managing stopwatch status and time
  const [isRunning, setIsRunning] = useState(false);
  const [time, setTime] = useState(0);

  // Ref for managing the interval
  const intervalRef = useRef();

  // useEffect for cleaning up the interval when the component is unmounted
  useEffect(() => {
    return () => {
      clearInterval(intervalRef.current);
    };
  }, []);

  // Function to handle the start button click
  const handleStart = () => {
    if (!isRunning) {
      setIsRunning(true);
      intervalRef.current = setInterval(() => {
        setTime((prevTime) => prevTime + 1);
      }, 1000);
    }
  };

  // Function to handle the pause button click
  const handlePause = () => {
    setIsRunning(false);
    clearInterval(intervalRef.current);
  };

  // Function to handle the reset button click
  const handleReset = () => {
    setIsRunning(false);
    setTime(0);
    clearInterval(intervalRef.current);
  };

  // Function to format time in mm:ss
  const formatTime = (seconds) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
  };

  // JSX structure for the stopwatch component
  return (
    <div style={styles.container}>
      <h1 style={styles.header}>Stopwatch</h1>
      <div style={styles.time}>{formatTime(time)}</div>
      <div style={styles.buttons}>
        <button style={styles.button} onClick={handleStart} disabled={isRunning}>
          Start
        </button>
        <button style={styles.button} onClick={handlePause} disabled={!isRunning}>
          Pause
        </button>
        <button style={styles.button} onClick={handleReset} disabled={isRunning}>
          Reset
        </button>
      </div>
    </div>
  );
};

// Styling for the stopwatch component
const styles = {
  container: {
    textAlign: 'center',
    margin: '50px auto',
    padding: '20px',
    border: '1px solid #ccc',
    borderRadius: '8px',
    maxWidth: '300px',
    backgroundColor: '#f8f8f8',
  },
  header: {
    fontSize: '24px',
    marginBottom: '10px',
    color: '#333',
  },
  time: {
    fontSize: '36px',
    fontWeight: 'bold',
    marginBottom: '20px',
    color: '#333',
  },
  buttons: {
    display: 'flex',
    justifyContent: 'space-between',
  },
  button: {
    padding: '10px',
    fontSize: '16px',
    fontWeight: 'bold',
    borderRadius: '4px',
    cursor: 'pointer',
    backgroundColor: '#4caf50',
    color: 'white',
    border: 'none',
    outline: 'none',
    width: '80px',
  },
};

// Export the stopwatch component
export default Stopwatch;

This code sets up the basic structure of our stopwatch component with the necessary state, functions, and styles.

Conclusion
You've successfully designed a stopwatch in React. This project demonstrates your ability to use React hooks, manage component state, and handle side effects. Feel free to customize the styles, add features, or explore other React concepts to enhance your stopwatch further. Good luck!

Did you find this article valuable?

Support Insightful Bytes by becoming a sponsor. Any amount is appreciated!