The React lifecycle seems to have a lot of hooks, with different calls to various states. In fact, it can be divided into three phases: initialization phase, update phase, and destroy phase. Let’s talk about these three stages in detail.

Complete flow chart of life cycle:

The first phase: the initialization phase

The constructor() function initializes the props and state values. The constructor inherits some methods from the parent class via super(props) and also creates this. Here are some methods of Component that we need to inherit and instantiate by passing props.

Then there is componentWillMount(), where the DOM element is not generated, so we can do some pre-processing here, but there are very few scenarios.

Next comes the Render phase, which essentially takes several actions. It is divided into three steps: virtual DOM tree construction, diff algorithm, page rendering.

At the end of the initialization phase is the life cycle for componentDidMount(). The page has already generated a DOM tree, but we need to do some init operations, such as making some pre-http requests. The entire initialization phase, with the exception of Render (), is performed only once in the entire lifecycle.

The second stage: update stage

The second phase is mainly about updating. These are also ticks with parameters in the lifecycle function.

  1. ComponentWillReceiveProps (nextProps) : this method will be received from the father has changed nextProps components, and then we take nextPorps and this. Compare the props, to see whether or not to do some update operations.

  2. ShouldComponentUpdate (nextProps, nextState): Should update or not? The lifecycle will receive the values of the nextProps and nextState parameters, and we can use those values to determine if I should refresh based on the scenario. Function returns a Boolean value of true: refresh | false: do not refresh, can be used for performance optimization, write more high quality code.

  3. Shouldcomponentwillupdate (nextProps, nextState): When shouldComponentUpdate returns true, it goes into this method, and then we do business with it, whether it’s HTTP requests or page logic adjustments.

  4. Then render…

  5. ComponentDidUpdate (preProps, preState): Similar to componentDidMount, but componentDidMount is executed only once during initialization. All subsequent Render operations enter componentDidUpdate. However, in ordinary use, this component is rarely used.

The third stage: destruction stage

ComponentWillUnmount (): This operation is mainly a few additional operations during the component destruction phase. For example, destroy removeEventListern, clearInterval, cleaTimeout, and some warnings. By the way, the warning is usually caused when we have some asynchronous requests completed, we need to update the DOM, and the component has been uninstalled. The general handling method is as follows:

Summary: React’s life cycle is not that complicated. (Note: Semantic coding is important.)