Introduction to Components And Functions
Necessary Concepts for the Project
Before getting started with the actual implementation of the stopwatch application, let’s look into the necessary concepts you need to know. In this lesson, we will look into the basic concept behind the actual working of the stopwatch application in JavaScript.
Components
Components play an important role in the React JS framework. Components are based on the ‘break it down to build it’ concept, which means each component is developed individually and then assembled to build a complete user interface. It provides:
- Component reusability across different parts of the application to reduce writing repeated codes.
- The efficient way to test each component, rectify the errors and modify only the specific component.
- Consistent user interface to ensure a uniform look and feel throughout the application.
Functions
The main logic of the stopwatch application can be written in the form of functions using JavaScript. This defines logic for actions like starting, stopping and resetting the digital timer in the application. Let’s look into three main functions we used for this application.
useEffect()
- useEffect function performs the side effects in the functional components.
- It is used for tasks like data fetching, event listeners or updating the DOM.
- Syntax:
| useEffect(() => { // CODE }, [dependencies]); |
useState()
- It allows you to add state to functional components.
- It's used to store and update dynamic values in the component.
- Syntax:
| const [state, setState] = useState(initialValue); |
useRef()
- It creates a reference to a DOM element or a mutable value.
- It is used to access DOM nodes directly or keep values that persist across renders.
- Syntax:
| const ref = useRef(initialValue); |
Formula to Calculate Time
To calculate the time, we have used Date.now() function to find out the current date and we are calculating the time from the date in hours, minutes, seconds and milliseconds. Let’s look at the formula we used to calculate the time.
let hours = Math.floor(elapsedTime / (1000 * 60 * 60));
let minutes = Math.floor((elapsedTime / (1000 * 60)) % 60);
let seconds = Math.floor((elapsedTime / (1000)) % 60);
let milliseconds = Math.floor((elapsedTime % 1000) / 10);
Here, the elapsed time is the current seconds or the time running after pressing the start button. It will be set and calculated in the next lesson.
In the next lesson, we will get into the actual implementation and styling of the application.


