By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
Coders GeekCoders Geek
  • Home
  • Linux
    • Linux Tutorials
    • Linux Tips
    • Linux Security
  • Programming
    • Python
    • Java
    • C++
    • R Programming
    • JavaScript
    • Frontend
    • Backend
  • Tech News
    • Latest Trends
    • Product Launches
    • Tech Events
    • Innovations
  • Operating Systems
    • Windows
    • macOS
    • Linux
    • Android
    • iOS
  • Reviews
    • Product Reviews
    • Software Reviews
    • Book Reviews
    • Tech Gadgets
Aa
Coders GeekCoders Geek
Aa
  • Home
  • Linux
  • Programming
  • Tech News
  • Operating Systems
  • Reviews
  • Home
  • Linux
    • Linux Tutorials
    • Linux Tips
    • Linux Security
  • Programming
    • Python
    • Java
    • C++
    • R Programming
    • JavaScript
    • Frontend
    • Backend
  • Tech News
    • Latest Trends
    • Product Launches
    • Tech Events
    • Innovations
  • Operating Systems
    • Windows
    • macOS
    • Linux
    • Android
    • iOS
  • Reviews
    • Product Reviews
    • Software Reviews
    • Book Reviews
    • Tech Gadgets
Copyright @ 2023 Coders Geek. All Rights Reserved.
Coders Geek > Blog > How To Create A Stopwatch Using Functional Component And React Hooks
Blog

How To Create A Stopwatch Using Functional Component And React Hooks

Prasandeep
Last updated: 2023/08/15 at 7:18 AM
By Prasandeep
Share
SHARE
How To Create A Stopwatch Using Functional Component And React Hooks

Stopwatches are commonly used in various applications to measure time intervals with precision and this question is also asked in many frontend interviews. In this tutorial, we’ll walk through the process of creating a simple stopwatch application using ReactJS. We’ll cover the basic components, state management, and event handling required to build this stopwatch.


Setting Up the Project

1. Create a New React App: 

Follow the same steps as mentioned in the previous examples to create a new React app named “StopwatchApp”.


2. Navigate to the App Directory: Change into the app directory:

cd StopwatchApp


3. Starting the Development Server: Start the development server:

npm start


Building the Stopwatch Component

1. Remove Default Files: Clear the contents of `App.js` and remove the unnecessary files, as explained in the previous examples.


2. Create a Stopwatch.js File: Inside the `src` folder, create a new file named `Stopwatch.js`.


3. Implement the Stopwatch Component:

In the `Stopwatch.js` file, use the following code to create the stopwatch component displaying time in hours, minutes, and seconds:

import React, { useState, useRef } from 'react';
import './Stopwatch.css';

const Stopwatch = () => {

  const [time, setTime] = useState(0);

  const [isRunning, setIsRunning] = useState(false);

  const timerRef = useRef();

  const formatTime = timeInSeconds => {

    const hours = Math.floor(timeInSeconds / 3600);

    const minutes = Math.floor((timeInSeconds % 3600) / 60);

    const seconds = timeInSeconds % 60;

    return `${hours.toString().padStart(2, '0')} : ${minutes

      .toString()

      .padStart(2, '0')} : ${seconds.toString().padStart(2, '0')}`;

  };

  const handleStart = () => {

    if (!isRunning) {

      setIsRunning(true);

      timerRef.current = setInterval(() => {

        setTime(prevTime => prevTime + 1);

      }, 1000);

    }

  };

  const handleStop = () => {

    clearInterval(timerRef.current);

    setIsRunning(false);

  };

  const handleReset = () => {

    clearInterval(timerRef.current);

    setTime(0);

    setIsRunning(false);

  };

  return (

    <div className="stopwatch">

      <h1>Stopwatch App</h1>

      <p>Time: {formatTime(time)}</p>

      <button onClick={handleStart} disabled={isRunning}>

        Start

      </button>

      <button onClick={handleStop} disabled={!isRunning}>

        Stop

      </button>

      <button onClick={handleReset}>Reset</button>

    </div>

  );

};

export default Stopwatch;

Integrating the Stopwatch Component


1. Update App.js:

In the `src` folder, open the `App.js` file and import the `Stopwatch` component:

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

function App() {

  return (

    <div className="App">

      <Stopwatch />

    </div>

  );

}

export default App;


Output: 


Styling the Stopwatch

You can create a `Stopwatch.css` file inside the `src` folder and define your styling rules to customize the appearance of the stopwatch.


Conclusion

You’ve successfully created a stopwatch application displaying time in hours, minutes, and seconds. This blog tutorial demonstrates how to format the time and integrate it with the functional component structure using React Hooks.

Sign Up For Daily Newsletter

Be keep up! Get the latest tech blog delivered straight to your inbox.

By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Previous Article Most Asked JavaScript Interview Questions – In-Depth Answers and Examples
Next Article Installing MySQL on Ubuntu 22.04 LTS – A Step-by-Step Guide
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Stay Connected

Facebook Like
Twitter Follow
Instagram Follow
Youtube Subscribe

Recent Post

  • Difference Between REST and SOAP In Cloud Computing
  • What Are Web Services In Cloud Computing?
  • What Is REST (Representational State Transfer) in Cloud Computing
  • What Is Service-Oriented Architecture (SOA) In Cloud Computing?
  • On-Demand Provisioning in Cloud Computing
Coders GeekCoders Geek
Follow US
Copyright @ 2023 Coders Geek. All RIghts Reserved.
  • Home
  • About Us
  • Contact Us
  • Write For Us
  • Privacy Policy
  • Terms Of Use
  • Advertise With Us
Welcome Back!

Sign in to your account

Lost your password?