React is an easy to use JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a digital clock app with React and JavaScript.
Create the Project
We can create the React project with Create React App.
To install it, we run:
npx create-react-app digital-clock
with NPM to create our React project.
Create the Digital Clock App
To create the digital clock app, we write:
import React, { useEffect, useState } from "react";
const date = new Date();
export default function App() {
const [dateTime, setDateTime] = useState({
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds()
});
useEffect(() => {
const timer = setInterval(() => {
const date = new Date();
setDateTime({
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds()
});
}, 1000);
return () => clearInterval(timer);
}, []);
return (
<div className="App">
<div>
{dateTime.hours}:{dateTime.minutes}:{dateTime.seconds}
</div>
</div>
);
}
We have the date
variable outside the App
component to set the initial date.
Inside App
, we have the dateTime
state, which we create with the useState
hook.
It’s set to an object with the hours
, minutes
, and seconds
properties.
We get the hours, minutes, and seconds with getHours
, getMinutes
, and getSeconds
respectively.
Then we add the useEffect
hook to get the latest date and time assigned to the date
variable.
We call setInterval
to set the latest date and time every second as indicated by the 2nd argument.
Then we call setDateTime
with the hours, minutes, and seconds values.
In the last line of the useEffect
callback, we return a function that calls clearInterval
with timer
to clear the timer when we unmount the component.
In the JSX code, we display the hours, minutes, and seconds.
Conclusion
We can create a digital clock app with React and JavaScript easily.