Elaborate on the React lifecycle

Life cycle before React v16.0

Actually, most teams may not necessarily follow up on upgrading to version 16, so it is necessary to master the lifecycle before version 16, especially since version 16 is also based on previous modifications

The first stage is the component initialization phase

That is to say, the constructor () of the class in the following code inherits the base class of React Component, which is the base class of React, in order to have methods such as render() and lifecycle that can be used. This also explains why function components cannot use these methods.

Super (props) is used to call the constructor method of the base class, and also injects the props of the parent component into the child component, allowing the child component to read (the props in the component are read-only and immutable, while the state is variable).

And constructor() is used to initialize some components, such as defining the initial content of this. state.

The second stage is the component mounting phase

This stage is divided into three periods: componentWillMount, render, and componentDidMount.

  • componentWillMount:

It is called before the component is mounted to the DOM and will only be called once. Calling this.setState here will not cause the component to re render. It can also advance the content written here to constructor (), so it is rarely used in projects.

  • render:

Based on the props and state of the component (without any retransmission or reassignment, and whether there is a change in the argument value, it can cause the component to be re rendered), return a React element (describing the component, i.e. UI), which is not responsible for the actual rendering work of the component. Afterwards, React itself renders the page DOM based on this element. Render is a pure function (the return result of a function only depends on its parameters; there are no side effects during function execution), and it cannot execute this. setState inside, which may have the side effect of changing the component state.

  • componentDidMount:

The component will be called only once after it is mounted to the DOM

The third stage is the component update phase

Before discussing this stage, it is necessary to clarify the update mechanism of the react component. The update of state caused by setState or the update of props caused by the re rendering of parent components will cause the re rendering of child components, regardless of whether there are changes in the updated state and props compared to before.

Uninstallation phase

There is only one lifecycle method at this stage: componentWillUnmount

  • componentWillUnmount

This method is called before the component is unloaded. You can perform some cleaning work here, such as clearing the timers used in the component and the DOM elements manually created in componentDidMount, to avoid memory leakage.