Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

You can also understand React Fiber, have you learned to waste?


May 31, 2021 Article blog


Table of contents


The article comes from the public number: Front-end Time House Author: Xiao Hao

The background in which Fiber appears?

In earlier Versions of React, before React16.8.

A large number of 同步计算任务 block the browser's UI rendering. By default, JS运算 页面布局 and 页面绘制渲染 are all 主线程 running in the browser, and they are 互斥 relationships.

If the JS operation continues to occupy the main thread, the page can not be updated in a timely manner, when we call setState update page, React will traverse all the nodes of the application, with the old dom node diff algorithm comparison, the lowest cost to update the page, 即使 so, the whole process is a one-off, 不能被打断 if the page elements are many, the whole process may take more than 16 milliseconds, the phenomenon of frame drop.

In response to this phenomenon, the React team optimized the workings of web pages at the framework level, and Fiber has been born.

When it comes to 16ms, let's look at a concept like this

Screen refresh rate

  • Most devices currently have a screen refresh rate of 60 times per second
  • The browser's rendering animation or the rate of each frame of the page also needs to be consistent with the refresh rate of the device screen.
  • The page is drawn frame by frame, and when the number of frames drawn per second (FPS) reaches 60, the page is smooth and less than this value, the user feels caton.
  • Budget time per frame is 16.66 milliseconds (1 second/60)
  • 1s 60 frames, so we try not to let a frame work more than 16ms when we write code

The birth of Fiber

The basic idea for solving the problem of the main thread being stun by JS for a long time is to cut the 运算切割为多个步骤 and complete it in batches. T hat is, after completing some of the tasks, 控制权交回 to the browser, giving the browser time to render the page again. After the browser is busy, continue with the previously unfinished tasks of React.

The legacy React 通过递归 using the JS engine's own function call stack, which executes until the stack is empty.

Fiber implements its own component call stack, which traverses the component tree as a list, giving it the flexibility to pause, continue, and discard tasks performed. T his is implemented using the browser's requestIdleCallback API. The official explanation is this:

window.requestIdleCallback() calls functions in turn during browser 空闲时期 which allows developers to perform 后台 or 优先级低 主事件循环 in the main event loop without having a critical event impact on delayed triggers such as animation and user interaction. Functions are generally executed in the order in which they are called first, unless the function has reached its timeout before the browser calls it.

The core usage of requestIdleCallback

  • Want to respond quickly to users, so that users feel fast enough not to block the user's interactive behavior
  • RequestIdleCallback enables developers to perform background and 低优先级 work on 主事件循环 without delaying critical events, such as animation and input responses
  • After the normal frame task is 没超过16ms indicating that the time is given, the task registered in requestIdleCallback is performed

RequestIdleCallback executes the process

 You can also understand React Fiber, have you learned to waste?1

What is Fiber?

Fiber is an execution unit

Fiber is an execution unit, and each time an execution unit is executed, React checks how much time is left and gives up control if there is no time

 You can also understand React Fiber, have you learned to waste?2

Fiber is a data structure

React's current practice is to use a linked list, represented internally by each VirtualDOM node as a Fiber which can be represented by a JS object:

const fiber = {
  stateNode, // 节点实例
  child,     // 子节点
  sibling,   // 兄弟节点
  return,    // 父节点
}

 You can also understand React Fiber, have you learned to waste?3

The coordination phase prior to Fiber

  • React 递归比对 VirtualDOM tree, identifies the nodes that 需要变动 and then updates them synchronously. This process is called Reconcilation (coordination)
  • During Reconcilation, React 一直占用 browser resources, one will cause the user-triggered event to go unresponsive, the other will cause the frame to drop, and the user may feel the caton

let root = {
  key: 'A1',
  children: [
    {
      key: 'B1',
      children: [
        {
          key: 'C1',
          children: []
        },
        {
          key: 'C2',
          children: []
        }
      ]
    },
    {
      key: 'B2',
      children: []
    }
  ]
}


function walk(element) {
  doWork(element);
  element.children.forEach(walk);
}


function doWork(element) {
  console.log(element.key);
}
walk(root);

Prior to The Advent of Fiber, React recursively traversed virtual DOM nodes, consuming browser resources, actively wasting performance, causing catalytic phenomena, and the coordination phase could not 被打断的

 You can also understand React Fiber, have you learned to waste?4

After The Advent Of Fiber, Some Fiber Scheduling Policies Allocate CPU ResourceS Rationally, Turning Their 协调阶段变成可被终端 giving CPU (Browser) Execution Power At The Right 适时 And Improving Performance Optimization.

 You can also understand React Fiber, have you learned to waste?5

The Fiber execution phase

There are two stages for each rendering: Reconciliation (coordination stage) and Comet (commit phase)

  • Coordination phase: This phase 可以被中断 to find out all node changes, such as 节点新增 删除 属性变更 and so on, using the Dom-Diff algorithm, which React 副作用 (Effects)
  • Commit phase: The side effects (Effects) calculated in the previous phase are performed at once. This stage must be performed 同步 and 不能被打断

Simple understanding of the words

  • Stage 1: Build the Fiber tree to arrive at 节点信息 that needs to be 更新 (Can 可打断
  • Phase 2: Nodes that will need to be updated are 批量更新 at once. ( 不可打断 )

Fiber's coordination phase can be interrupted by higher-priority tasks, such as keyboard input.

The interrupted nature of Stage 1 allows 优先级更高的任务先执行 greatly reducing the probability of a page falling frames at the framework level.

Fiber performs the process

The render phase

Fiber Reconciliation generates a Fiber 树 as part of the Diff calculation. This tree is 生成 by adding additional information to the Virtual DOM 树 which is essentially a linked list.

 You can also understand React Fiber, have you learned to waste?6

Commit submission phase

The Fiber tree is generated once when it is first rendered. W hen Diff is needed 后续 a new tree is generated based on the information of the existing tree and the latest Virtual DOM. E ach time the new tree generates a new node, control is returned to the main thread to check for higher priority tasks to perform. If not, continue the process of building the tree.

1. If a higher priority task is required in the process, Fiber Reconciler discards the tree being generated and executes it again when idle.

2. During the construction of the Fiber tree, Fiber Reconciler saves the updated node information in Effect List and updates the node in bulk as Phase 2 executes.

Details are expanded

How does the render stage traverse to generate the Fiber tree?

<div>

  

    

      

      

    

    

  
</div>

  • Traverse from vertex
  • If you have your first son, traverse your first son first
  • If there is no first son, this node traversal is complete
  • If there is a brother traversal the brother
  • If there is no next brother, return the parent node identity to complete the parent node traversal, if there is an uncle traversal uncle
  • There is no parent node traversal end

 You can also understand React Fiber, have you learned to waste?7

How does the commit phase come about?

Analogy Git branching, one from the old tree, adding, deleting, and updating operations in a new branch, and submitting after testing.

 You can also understand React Fiber, have you learned to waste?8

Above is W3Cschool编程狮 about the React Fiber you can also understand, learned to waste the relevant introduction, I hope to help you.