1. Why was React Fiber introduced and what problems did it solve? 2

What problems does React Fiber solve?

Because the previous structure caused the page to stall.

Why does it cause page lag?

React calls the Render and setState methods to render and update. There are two stages:

  • Reconciler scheduling stage: A top-down recursive algorithm iterates through the data to generate a new Virtual DOM. Through the diff algorithm, find the elements that need to be updated and put them in the update queue. This strategy cannot be interrupted, and once started, the task will not be pushed off the stack until the entire virtualTree calculation is complete. However, the browser’s rendering engine is single-threaded, and if there is a user interaction or animation task on the main thread at this time, it cannot be handled immediately, affecting the experience.
  • Rendering stage: according to the rendering environment, the update queue is traversed, the API of the rendering host environment is called, and the corresponding elements are updated to render.

React Fiber How to solve the page lag problem

Divide the scheduling phase into a series of small tasks. Add one node at a time to the task and see if there is time to move on to the next task. If so, continue. No will be suspended, in the main thread is not busy to continue. Do a little bit at a time, and then return time control to the main thread. Rather than long occupation as before, so as to achieve the task of suspension, recovery, flexible control. The Node here is the Fiber Node.

Changes after Fiber was introduced – life cycle changes

Before Fiber was introduced, our life cycle looked like this:

Fiber was introduced to break tasks into small nodes that might be interrupted/resumed before Render. Causes the life cycle before render to happen multiple times.

So we scrapped the three life cycles prior to Render

  • componentWillMount
  • componentwillRecieveProps
  • componentWillUpdate

Replace:

var LIFECYCLE_SUGGESTIONS = {
  UNSAFE_componentWillMount: 'componentDidMount',
  UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
  UNSAFE_componentWillUpdate: 'componentDidUpdate'
};
Copy the code

Given the solution, two new life cycles are added:

  • GetDerivedStateFromProps replaces the Will lifecycle
  • GetSnapshotBeforeUpdate executes after Render. When the DOM element has not been updated, give it a chance to get the DOM information and calculate the snapshot

The life cycle becomes:

All content is not original, original see: zhuanlan.zhihu.com/p/44942360