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')
);
Explanation
Line 4: The
datevariable is initialized with the current date.Line 6–12: To update the
datestate, auseEffecthook is run when the component is mounted.Line 7–9: In the
useEffecthook, asetInterval()function is run, which updates the state every 1000 milliseconds (1 second). This allows thedatevariable to be updated with the current date. ThesetInterval()function is stored in a variable calledintervalIdwhich uniquely identifies the interval.Line 11: When the
Appcomponent is unmounted, that is, removed from the Document Object Model (DOM), theclearInterval()method is called to remove the timed action of thesetInterval()method and stop it from running.Line 14–18: In the
return()method, thedatevariable is converted totimewith thetoLocaleTimeString()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')
);
Explanation
Line 4–8: The
timevariable is initialized as an object with properties ofminutes,hours, andsecondsset to the current time.Line 10–21: To update the state, a
useEffecthook is run when the component is mounted.Line 11–18: In the
useEffecthook, asetInterval()function is run, which updates the state every 1000 milliseconds (1 second). Thedatevariable gets the current date object. Thetimeproperties are then updated with the current time by thesetTime()method. ThesetInterval()function is stored in a variable calledintervalIdwhich uniquely identifies the interval.Line 20: When the
Appcomponent is unmounted, that is, removed from the Document Object Model (DOM), theclearInterval()method is called to remove the timed action of thesetInterval()method and stop it from running.Line 23–27: The
convertToTwoDigit()function converts thenumberpassed as a parameter to a 2-digit string value.Line 29–36: In the
return()method, thetimeproperties are accessed and passed as arguments to theconvertToTwoDigit()function.Line 34: A conditional statement checks if the hour is equal to or greater than 12. If the condition is true,
PMis displayed, otherwiseAMis shown.