Create a React App Displaying the Current Date and Time Using Hooks

This is the first post in creating the frontend of a clocking in app on React. In this post we’ll go through creating a basic React app and displaying the current date and time using Hooks.

Yousef Ahmed
Create a Clocking in System in React
3 min readMay 28, 2020

--

1. Create the React App

First things first, we need to create a React App for all our frontend babies (components) to live in. Luckily there is a shortcut that you can use in your terminal to create the basic skeleton of a React app. You should navigate to a suitable location, then in your terminal:

Let the process finish before opening clocking_system_frontend in your favourite editor (obviously VS Code 😉)

2. Create your Main component

Running the command above by default creates an App.js file in your src folder. To check your app works as expected, you can remove all the contents, and replace with the standard ‘Hello World!’

Run the command below in you terminal:

A browser with ‘Hello World’ should pop up if everything is working properly (on localhost:3000). Once you are happy that everything is going smoothly, we can start the fun stuff.

3. Date and Time

We’re going to start with building a component that we can have on the main page to display the current date and time. This would be especially useful for the user to know what time they are clocking in/out at.

Since we’ll be using hooks, our states can be set up as follows:

When new Date() is used, the initial states of date is set to the current date. However, this value won’t change as the time and date changes, and will stay constant as to when the component was first rendered. This wouldn’t be ideal if the app was on standby and would be fairly inconvenient to refresh the page for the current date/time to be displayed.

As mentioned, new Date() will set the current date. So we essentially want to set our state as a new Date() object every second or so. Setting our state is as easy as calling setDate(new Date()), now we can worry about how often we want this function to be called:

useEffect() has many functional uses, for our particular need we are trying to make sure the component is updated. Within the Effect Hook, our date state (rhyme-time) is set at an interval, every 1000ms (1s). The clean up function is there to reset the whole process and avoid any memory leaks.

To see if this is actually working we can add a return statement, using the method toLocaleTimeString() that will extract just the time from the whole object and return it as a string:

The full component will look like this:

And place the completed component back into our App.js:

If we our app is running, we should be able to go back to the browser and viola!

For further information on the cleaning up function used in the Effect Hook:

https://dev.to/pallymore/clean-up-async-requests-in-useeffect-hooks-90h

--

--