How to create a dynamic digital clock in React

A dynamic digital clock displays the current time in hours, minutes, and seconds on digital devices, including wristwatches, websites, phones, and laptops.

Coding example 1

Here's an example that explains how to create a dynamic digital clock in React:

import React from 'react';
import './index.css';
import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);
Displaying dynamic clock in React application

Explanation

  • Line 4: The date variable is initialized with the current date.

  • Line 6–12: To update the date state, a useEffect hook is run when the component is mounted.

  • Line 7–9: In the useEffect hook, a setInterval() function is run, which updates the state every 1000 milliseconds (1 second). This allows the date variable to be updated with the current date. The setInterval() function is stored in a variable called intervalId which uniquely identifies the interval.

  • Line 11: When the App component is unmounted, that is, removed from the Document Object Model (DOM), the clearInterval() method is called to remove the timed action of the setInterval() method and stop it from running.

  • Line 14–18: In the return() method, the date variable is converted to time with the toLocaleTimeString() method.

Coding example 2

An alternative code, which gets the time in hours, minutes, and seconds separately, is explained below:

import React from 'react';
import './index.css';
import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);
Alternative way of displaying dynamic clock in React application

Explanation

  • Line 4–8: The time variable is initialized as an object with properties of minutes, hours, and seconds set to the current time.

  • Line 10–21: To update the state, a useEffect hook is run when the component is mounted.

  • Line 11–18: In the useEffect hook, a setInterval() function is run, which updates the state every 1000 milliseconds (1 second). The date variable gets the current date object. The time properties are then updated with the current time by the setTime() method. The setInterval() function is stored in a variable called intervalId which uniquely identifies the interval.

  • Line 20: When the App component is unmounted, that is, removed from the Document Object Model (DOM), the clearInterval() method is called to remove the timed action of the setInterval() method and stop it from running.

  • Line 23–27: The convertToTwoDigit() function converts the number passed as a parameter to a 2-digit string value.

  • Line 29–36: In the return() method, the time properties are accessed and passed as arguments to the convertToTwoDigit() function.

  • Line 34: A conditional statement checks if the hour is equal to or greater than 12. If the condition is true, PM is displayed, otherwise AM is shown.

Free Resources