preface

React 15 and React 16 React 15 and React 16 The characteristics and matters needing attention of related functions are summarized. By learning and comparing the life cycle, we can understand the Fiber design concept and design purpose of React 16, and then have a concrete understanding of the life cycle changes of React 16 and React 16.

Life cycle comparison

The React 16.3 version flow chart shows the life cycle since React 16.

The reason for showing React 16.3 is that after React 16.4, the React lifecycle underwent a minor tweak over the previous version. We’ll talk about that later.

Mounting stage

Here is a diagram of the initial rendering process of components for version 15 and 16 as follows:

The main difference between React 15’s and React 16’s life cycle remount phases can be seen in the figure above. Deprecated componentWillMount and added getDerivedStateFromProps.

Updating stage

React 15 vs. React 16.3

React 16: Remove componentWillUpdate and add getSnapshotBeforeUpdate. The Render method has also been improved. Before React 16, render had to return a single element, while React 16 allows Wimbledon to return an array of elements and strings.

GetDerivedStateFromProps parsing

Call the rules
static getDerivedStateFromProps(props, state)
Copy the code
The characteristics of
  1. GetDerivedStateFromProps is a static method. Static methods do not depend on the instance of the component, so this is not accessible from within this method. If you attempt to access this, an error will be reported.
  2. This method takes two arguments:props, state, representing the props received by the current component from the parent component and the state of the current component itself, respectively.
  3. The getDerivedStateFromProps lifecycle function must return the return value of an object or an error will be reported. If you don’t want to return anything else, you can return a NULL (this is because the return value is needed to update (derive) the component’s state).
Pay attention to
  1. The update of the getDerivedStateFromProps lifecycle function to state is a targeted update for a property, not an override update.

  2. GetDerivedStateFromProps is not a substitute for componentWillMount. It is to replace componentWillReceiveProps. Because the getDerivedStateFromProps lifecycle function has one and only one purpose: derive/update state using props.

  3. The getDerivedStateFromProps lifecycle function “mirrors” during both the mount and update phases.

  4. React 16.3 differs from React 16.4. In React 16.3, the getDerivedStateFromProps lifecycle function is triggered only when the parent props is updated. In the >= React 16.4 version, the getDerivedStateFromProps lifecycle function is triggered when the component props is updated, setState(), and forceUpdate().

    The React version 16.3

    >= React 16.4

  5. GetDerivedStateFromProps cannot completely draw equal-sign componentWillReceiveProps, and cannot be used in componentWillReceiveProps do, 100% migration to getDerivedStateFromProps.

  6. GetDerivedStateFromProps is defined as static, so the component instance’s this is not available, This makes it impossible to do anything inside it like this.fetch(), irrational this.setstate (the kind that leads to an infinite loop) that might produce side effects.

Design intent

The purpose of React 16 is to ensure that the behavior of lifecycle functions is more controllable and predictable, which ultimately helps developers avoid bad programming and lifecycle abuse, and also paves the way for the new Fiber architecture.

GetSnapshotBeforeUpdate parsing

Call the rules
getSnapshotBeforeUpdate(prevProps, prevState) {

  // ...

}
Copy the code
The sample
GetSnapshotBeforeUpdate (prevProps, prevState) {console.log("getSnapshotBeforeUpdate method execution "); // getSnapshotBeforeUpdate(prevProps, prevState) {console.log("getSnapshotBeforeUpdate method execution "); return "haha"; } // componentDidUpdate(prevProps, prevState, valueFromSnapshot) {console.log("componentDidUpdate method executes "); Console. log(" Value obtained from getSnapshotBeforeUpdate is ", valueFromSnapshot); }Copy the code
The characteristics of
  1. The return value of getSnapshotBeforeUpdate is given as the third parameter to componentDidUpdate.
  2. The execution time is after the Render method and before the actual DOM update. In this phase, we can get the real DOM before and after the update and the state&props information before and after the update.
Design intent

GetSnapshotBeforeUpdate is designed to “cover all use-cases for componentWillUpdate with componentDidUpdate.” GetSnapshotBeforeUpdate needs to work with componentDidUpdate.

Unmounting: Components are uninstalled

The life cycle of the uninstall phase is exactly the same as that of React 15. Only the life cycle of componentWillUnmount is involved.

React 16 Why change things twice?

Fiber architecture brief analysis

Fiber is a rewrite of the React core algorithm. The most important point is that Fiber makes the rendering process asynchronous instead of synchronous.

background

Prior to React 16, every time we triggered a component update, React would build a new virtual DOM tree and diff with the previous virtual DOM tree to implement a directed UPDATE to the DOM. This is a recursive process.

The characteristics of

Only when the lowest level call returns does the rendering process begin to return layer by layer. This long, uninterrupted update process.

risk

Once synchronous rendering starts, it holds onto the main thread until the recursion is complete. During this process, the browser can’t handle anything beyond rendering and enters a state where it can’t handle user interaction. So if the rendering time is slightly longer, the page runs the risk of stalling or even getting stuck.

Current Solution

The Fiber architecture introduced by React 16 addresses this risk: Fiber breaks up 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.

During this process, the rendering thread can be interrupted, which is called “asynchronous rendering”.

Lifecycle workflow

An important feature of the Fiber architecture is asynchronous rendering that can be interrupted. But there is a principle to this interruption.

The React 16 lifecycle is divided into render and COMMIT phases based on the “can’t be interrupted” criterion, and the Commit phase is subdivided into pre-commit and COMMIT phases. The life cycle covered by each phase is shown below:

Characteristics of the

  • Render phase: Pure and without side effects, may be suspended, terminated, or restarted by React.

  • Pre-commit phase: DOM can be read.

  • Commit phase: You can use DOM, run side effects, and schedule updates.

In general, the Render phase allows interruption during execution, whereas the Commit phase is always executed synchronously.

Design intent that can be interrupted during the Render phase

Since the render phase is actually “invisible” to the user, even if interrupted and restarted, the user is not aware of it.

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.

Elaborate on the thinking behind the life cycle of “old and new”

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.

Things you are used to doing in the life cycle beginning with “componentWill” may include, but are not limited to:

  • SetState ();
  • Fetch initiates an asynchronous request.
  • Manipulate the real DOM.

The problems (or non-necessity) with these operations include, but are not limited to, the following three points:

  1. It’s perfectly possible to migrate to other life cycles (especially componentDidxxx).

    For example, making asynchronous requests in componentWillMount.

  2. With Fiber’s asynchronous rendering mechanism, this can lead to serious bugs.

    Suppose you make a payment request in componentWillxxx. Since the life cycle in the Render phase can be repeated, after componentWillxxx is interrupted + restart several times, it will issue multiple payment requests.

  3. Even if you don’t have asynchrony enabled, React 15 still kills a lot of people.

    Such as in componentWillReceiveProps and componentWillUpdate setState abuse lead to repeated render loop

conclusion

The main motivation for the React 16 lifecycle transformation was to accommodate the asynchronous rendering mechanism brought about by the Fiber architecture. During this process, the React team kept improving and implemented mandatory best practices for the chronically abused parts of the life cycle. All of this work is done to ensure data and view security in Fiber and to ensure that the behavior of the lifecycle method is pure, controllable, and predictable.

reference

  • React