The React lifecycle consists of the following phases: component initialization, component uninstallation, and component uninstallation
1. Initialization phase
2. Update phase
3. Uninstall phase
To learn more about the React lifecycle, let’s take a look at the React lifecycle from React15
The life cycle of Act15
Initialization phase
During the initialization phase, the lifecycle follows the following process, which is executed only once in the lifetime of the component
Constructor: Used to initialize State
ComponentWillMount: Generates virtual DOM via render function before triggering, chicken ribs
Render: Generate a new virtual DOM through Diff algorithm
ComponentDidMount: Triggered when a component is rendered, it can manipulate the real DOM or make asynchronous data requests
Update the stage
There are two types of updates:
- Updates triggered by parent component updates
- Updates triggered by its own State change
Note:componentWillReceiveProps()
Is triggered by an update to the parent component, andprops
It doesn’t matter if it changes
Here is a key understanding
shouldComponentUpdate(nextProps,nextState)
This is a point that React provides for performance optimizationThe render function is used to generate the new virtual DOM. This process is time-consuming. ShouldComponentUpdate () is executed before the render function. It returns a Boolean value (true by default), and when true is returned, the update lifecycle process will continue, otherwise it will not continue
An 🌰
shouldComponentUpdate(nextProps,nextState){
if(...). {return true
}else{
return false}}Copy the code
Unloading phase
When the component is unmounted, the componentWillUnmount() method is executed
conclusion
In Act15, the lifecycle can be divided into three phases: initialization phase, update phase, and uninstall phase
Initialization phase: Constructor, componentWillMount, Render, componentDidMount
Update phase: componentWillReceiveProps, shouldComponentUpdate componentWillUpdate, render, componentDidUpdate
Unloading stage: componentWillUnmont
Note here is the update stages, componentWillReceiveProps is triggered by the parent component updates, as long as the parent component updates, child components of the life cycle will be implemented, has nothing to do with props. ShouldComponentUpdate can also be used for performance optimization
The lifecycle of React16
After learning the life cycle of Act15 above, take a look at the life cycle of Act16
Take a quick look at the life cycle diagram in Act16
In the life cycle of Act16, the former componentWillMount and componentWillUpdate methods were removed and getDerivedStateFromProps was used instead. At the same time, a getSnapshotBeforeUpdate method is added between the Render method and componentDidUpdate in the update phase. Here’s a closer look at how React does this and how these new life cycles are used
An 🌰
- The parent component
- Child components
- Print sample
View the sample source code
Initialization phase (mount)
To compare the differences between Act15 and Act16, take a look at the following figure
For instance, act16 has removed componentWillMount and added getDerivedStateFromProps. It is important to note that getDerivedStateFromProps not used instead of componentWillMount method, it is used to replace the componentWillReceiveProps.
As for the componentWillMount method, which is inherently cumbersome and often used inappropriately, it was removed in Act16
Let’s focus on the getDerivedStateFromProps method. As the name indicates, this method is used to update its own state** based on the props passed by the parent component
1. getDerivedStateFromProps
Is a static method. The declared use is static
static getDerivedStateFromProps(props,state){
return newState
}
Copy the code
2. getDerivedStateFromProps
Receives two parameters, one passed by the parent componentprops
And its ownstate
The sample with 1
3. getDerivedStateFromProps
You must return a value in object format, or the console will be warned
The return value will be used to update the existing state(it will not overwrite the existing state, but will only be updated if the property is not present in the original state). If no update is required, return null
Update phase (component update)
In the initial stage, we focus on the getDerivedStateFromprops method, we have said above, getDerivedStateFromprops is used to replace componentWillReveiveprops method. According to the React official description
This new life cycle covers with componentDidUpdate outdated componentWillReceiveProps all use cases.
But Why?
Here I quote the teacher’s explanation of React in a simple way. I think his explanation is easy to understand and cannot be surpassed
Back to getDerivedStateFromProps this API, relative to that of early componentWillReceiveProps, it was made a “reasonable subtraction”. The determination to do this is illustrated by the fact that getDerivedStateFromProps is defined as a static method directly — the static method does not get the component instance’s this inside, This prevents you from doing anything in getDerivedStateFromProps like this.fetch(), irrational this.setState (the kind that causes an infinite loop) that might have side effects.
Therefore, behind the alternative componentWillReceiveProps getDerivedStateFromProps life cycle, React 16 enforces the best practice of using only getDerivedStateFromProps to map props to state. The purpose is to ensure that the behavior of life cycle functions is more controllable and predictable, and to help developers avoid unreasonable programming methods and life cycle abuse from the root; It also paves the way for a new Fiber architecture.
In addition to the getDerivedState method, in update phase, React16 also removed the componentWillUpdate method and added the getSnapshotBrforeUpdate method. This method after the Render method, ComponentDidUpdate is executed before the real DOM update (to get the real DOM before and after the update and the State&props information). The method requires a return value as the third argument to componentDidUpdate. Since this method is used in few scenarios, it is not described in detail here
Unloading phase
With React15
conclusion
Relative to ACT15, the Life cycle of Act16 removes the componentWillMout and componentWillUpdate methods And use getDerivedStateFromProps method replaces the previous componentWillReceiveprops, makes life cycle of the React pure, only used to do special things, avoid a lot of business logic code embedded in the life cycle, and pave the way for the Fiber structure
First understanding of Fiber architecture
What is Fiber? Fiber changes to React?
Fiber is React16’s rewrite of the React core algorithm
FIber will make the synchronous rendering process asynchronous
What are the risks of the React history algorithm?
Prior to React16, every component update would trigger React to build a new virtual DOM tree, which could be updated in a specific way by comparing it with the diff algorithm of the last virtual DOM tree. This process is a recursive process, with the call stack very deep, and only when the bottom layer returns does the rendering process begin to return layer by layer. And this process of long and cannot be interrupted, would provide a huge risk to the user experience: synchronous rendering once you begin, will firmly seize the thread, until to complete recursive, the constant browser not handle any rendering outside, will enter a state of not be able to process the user interaction, the page is likely to be stuck.
How does Fiber handle rendering?
Fiber breaks down a large update task into many smaller tasks. Each time a small task is completed, the render thread passes the main thread back to see if there is any higher-priority work to be done, making sure that other tasks don’t starve to death, thus avoiding lag caused by synchronous rendering. In this process, the rendering thread is no longer “gone forever”, but can be interrupted, this is called “asynchronous rendering”.
Back to the life cycle
When the life cycle diagram is presented at the beginning, careful students will notice that on the left side of the diagram below, React divides the life cycle into the following three phases
- Render: pure and without side effects, may be suspended or terminated, restart
- Pre-commit phase: DOM can be read
- Commit phase: You can use DOM, run side effects, and schedule updates
Why is it divided like this?
In general, the Render phase allows interruption during execution, whereas the Commit phase is always executed synchronously.
Why is it designed this way? To put it simply, the render phase is “invisible” to the user, so even interrupting and restarting the render phase will be insensitive to the user. The commit phase involves rendering the actual DOM, and even the craziest framework doesn’t dare change the view in front of the user, so the process must be stabilized by synchronous rendering.
Abolishing the link between the lifecycle and Fiber
With Fiber, the Render phase allows pauses, terminations, and restarts. When a task is interrupted in the middle of execution and the next time the render thread takes back control, the task is restarted in the form of “repeat the entire task” rather than “pick up where you left off”. This leads to the possibility of repeated execution of the render phase lifecycle.
With that in mind, let’s take a look at what life cycles React 16 intends to deprecate:
ComponentWillMount;
ComponentWillUpdate;
ComponentWillReceiveProps.
What these life cycles have in common is that they are all render phases, they can be repeated, and because these apis have been abused over the years, there is a significant risk of repeated execution.