1. Why is scheduling needed?

We all know that JS and rendering engines are mutually exclusive. If JS is executing code, rendering engine work will stop. If we have a complex composite component that needs to be rendered again, the call stack can be very long. If the call stack is too long, and if there are complex operations in the middle, it can block the rendering engine for a long time and cause a bad user experience. Scheduling is to solve this problem

2. React Scheduling process?

  • First, each task has its own priority, which can be calculated by adding the current time and the constant corresponding to the priorityexpriationTime.High-priority tasks interrupt low-priority tasks
  • Determine the current task before schedulingIs late, expired without scheduling, direct callport.postMessage(undefined), so that expired tasks can be executed immediately after rendering
  • If the task has not expired, passrequestAnimationFrameStart the timer and call the callback method before redrawing
  • In the callback method we first needCalculate the time of each frame and the time of the nextAnd then executeport.postMessage(undefined)
  • channel.port1.onmessageWill be called after rendering, and in this process we first need to determineWhether the current time is less than the next frame time. If it’s less than that, it means we have free time to perform tasks. If it is greater than that, it means that the current frame has no free time, at which point we need to determine if any task is expired,If it’s overdue, you still have to perform this task. If not, the task can be pushed to the next frame to see if it can be executed

Reference source: https://yuchengkai.cn/react/2019-06-04.html#%E6%96%87%E7%AB%A0%E7%9B%B8%E5%85%B3%E8%B5%84%E6%96%99

3. How does Fiber work?

Older React renders recursively, 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 in a linked list with the flexibility to pause, continue, and drop tasks. This is done using the browser’s requestIdleCallback API