State and Lifecycle
In this section, we will learn how to make the Clock component truly reusable and encapsulated. It will set up its own timer and update itself every second.
Hello, world!
It is 6:46:07 AM.
However, it misses a crucial requirement: the fact that the Clock sets up a timer and updates the UI every second should be an implementation detail of the Clock.
Converting a Function to a Class
- Create an ES6 class, with the same name, that extends React.Component.
- Add a single empty method to it called render().
- Move the body of the function into the render() method.
- Replace props with this.props in the render() body.
- Delete the remaining empty function declaration.
Adding Local State to a Class
We will move the date from props to state in three steps:
- Create an ES6 class, with the same name, that extends React.Component.
- Add a class constructor that assigns the initial this.state:
- Remove the date prop from the Clock element:
It is 6:46:07 AM.
Adding Lifecycle Methods to a Class
- In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.
- We want to set up a timer whenever the Clock is rendered to the DOM for the first time. This is called “mounting” in React.
- We also want to clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React.
- We can declare special methods on the component class to run some code when a component mounts and unmounts:
6:46:07 AM.
Formatted date is 6:46:07 AM.
Using State Correctly
There are three things you should know about setState().
State Updates May Be Asynchronous