React source code analysis. Life cycle call sequence

js_2028 2023-01-25 21:32:29 阅读数:778


Execution of life cycle at each stage

The cycle of function component hooks will be explained in the hooks chapter. The mission cycle of this chapter is mainly for class components. See the following figure for the life cycle execution of each stage:

react source code 11.1

  • render stage:

    1. When mounting: the component will first go through constructor, getDerivedStateFromProps, componnetWillMount, render
    2. When updating: the component will first go through componentWillReceiveProps, getDerivedStateFromProps, shouldComponentUpdate, render
    3. error: getDerivedStateFromError will be called
  • commit stage

    1. When mounting: the component will experience componnetDidMount
    2. When updating: the component will call getSnapshotBeforeUpdate, componnetDidUpdate
    3. When unMounting: call componnetWillUnmount
    4. When error: call componentDidCatch

The red part is not recommended to be used. It should be noted that the execution order of the life cycle of the commit phase is executed in each sub-phase of the mutation. You can review the previous chapter

Next, based on an example, I will explain the specific order of updating during mount and update:

react source code 11.2

react source code 11.3

Related reference video explanation: Enter learning

  • When mounting: First, the wip fiber nodes will be built in sequence in a depth-first manner and then switched to current fiber. In the render phase, the constructor, getDerivedStateFromProps/componnetWillMount, and render of each node will be executed in sequence. In the commit phase, that is, depth-firstWhen traversing upward bubbling, execute the componnetDidMount of the nodes in turn
  • When updating: the wip fiber tree will also be constructed with depth priority, and the child nodes will be diffed during the construction process. In the render phase, if there is a change in the existing node, such as c2 in the above figure, then mark this node Update Flag, and then execute getDerivedStateFromProps and render. In the commit phase, the getSnapshotBeforeUpdate and componnetDidUpdate of the node will be executed in sequence