React Clock
Let’s build a digital clock that updates every second.
To start, create a new React app called clock
using create-react-app.
$ npx create-react-app clock
$ cd clock
$ npm start
Open your web browser to http://localhost:3000/ to see the standard React welcome page. We only need to update the src/App.js
file in this tutorial.
Clock component
Our first task to is create a new Clock
component and include it as a child to the existing App
component. Let’s have it just say “Clock” to start.
// src/App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
return (
<div>
<Clock />
</div>
);
}
}
class Clock extends Component {
render() {
return (
<div>
<h1>Clock</h1>
</div>
);
}
}
export default App;
Static Time
Now let’s output the current at page load in our app. This won’t automatically update yet. First we can create our initial state and set it to the current time. Then we can output it using toLocaleTimeString()
so it represents the current local time.
// src/App.js
...
class Clock extends Component {
state = {
time: new Date()
};
render() {
return (
<div>
<h1>Clock</h1>
<h2>It is {this.state.time.toLocaleTimeString()}.</h2>
</div>
);
}
}
export default App;
Updating Time
First we need to create a custom method tick
that sets our state to the current time. Then we use componentDidMount
to create a timer.ID
that will update the state every second (1,000 milliseconds) and then componentWillUnmount
itself immediately after.
// src/App.js
class Clock extends Component {
state = {
time: new Date()
};
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
time: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.time.toLocaleTimeString()}.</h2>
</div>
);
}
}
Conclusion
In this basic example we created a clock with the current time that updates itself every second. We’re using state to manage our time
and lifecycle methods to update this time every second. Enjoy!
Want to learn more React? I have a list of recommended React books and JavaScript books.