What Is React Fiber? (key notes from classic lectures)

What is React Fiber?

Fiber = {...}
Fiber reconciler = current React reconciler based on Fiber
(React >= 16)

  • complete rewrite of React that fixed long-standing issues
  • offers incredible opportunities for the future

A Fiber in React is just a plain JS object with some properties

Fiber's main goals

Fiber Focuses on Animations And Responsiveness
It can:

  • It can split work into chunks and prioritize tasks
  • pause work and come back to it later
  • reuse previously completed work or maybe abort it if it's not needed

Fiber is asynchronous <<

Old Reconciler: Stack
  • stack was syncronous
  • worked like a stack
  • had to work until the "stack" was empty, it cound'b interrupted.

Stack was synchronous and with that come some major limitations

Is fiber all about performance ?

While Fiber comes with significant performance increases, it's not really about them.
It's about the fundamental way React work

  1. Fiber makes React faster, but it makes it smarter as well
  2. Fiber also improves the development of React

The implementation of Fiber

🚨 Fiber is just a plain JS object with some properties
The core underlying idea is that Fiber also represents a unit of work

⭐⭐⭐ 2 Reconciler Phases

【Fiber = Unit of Work】

🥇 render phase(processing
🥈 commit phase(committing

Fiber架构对堆栈调用执行的任务进行拆分,拆分成可独立运行的任务
充分的利用浏览器的工作机制,提升性能
Fiber架构:解决性能问题和提升调度能力,重新组织渲染过程
--------------------- Render Phase Start -------------------
-> Reconciliation Phase
Initialize/Update Fiber Tree
* Create Root Fiber
* Clone Fibers for updates
* Link Old and New Fibers
* Handle Offsreen and Hidden Components
* Process Legacy Context API
* Assign Return Pointer and Child Pointer
* Calculate Update Priority based on Lane Strategy
* Handle Strict Mode Warnings and DevTool Integrations
-> Begin Work
* Render Component
* Determin Changes
* Schedule Updates
* Handle Context Providers
* Handle Error Boundaries
* Handle Suspense and Lazy Loading
* Process useMemo and useCallback
* Detect Concurrent Mode and Udpate Priority
* Handle Event Handlers in Concurrent Mode
* Process useContext Hook
* Process useReducer Hook
* Handle useImperativeHandle Callbacks
-> Complete Work
* Create Work In Progress Tree
* Process Side-Effects
* Merge New Fibers with Old Fibers
* Check for Interrupted Work
* Update Memoized State and Props
* Compute Expiration Time for Updates
* Handle Profiler Component and Timing Metrics
* Process useTransition Hook
* Process useDeferredValue Hook
-> Task Splitting
* Prioritize Tasks
* Defer Low Priority Tasks
* Utilize Browser Idle Time
* Check for Uncommitted Updates
* use Lane Strategy for Scheduling and Prioritization
* Handle Time Slicing in Concurrent Mode
--------------------- Render Phase End -------------------
--------------------- Commit Phase Start -------------------
-> Before Mutation Phase
* Snapshot Lifecycle
* getSnpshotBeforeUpdate
* Call getDerivedStateFromProps
* Call static getDerivedStateFromError in Error Boudaries
* Process Strict Mode Double Render
-> Mutation Phase
* Execute Side-Effects
* Insert/Update/Delete DOM Elements
* Process Ref Updates
* Handle Forward Refs
* Handle Passive Effects
* Commit Hydration for Server-Rendered Components
* Invoke componentDidCatch in Error Boundaries
* Process useMutatbleSource Hook Updates
-> Layout Phase
* componentDidUpdate
* componentDidMount
* FLIP Animation Techniques
* Apply Accessibility Changes
* Apply Direactionality Changes
* Handle ResizeObserver Callbacks
* Apply CSS Variables and Custom Properties
* Handle IntersectionObserver Callbacks
* Process useLayoutEffect Callbacks
-> Passive Phase
* useEffect callbacks
* Clean up Previous Effects
* Interact with External Libraries and APIs
* Schedule Passive Effect Cleanup
* Handle Batched Updates
* Manage Custom React Renderers
--------------------- Commit Phase End -------------------
🥇 render phase
  • this phase is asynchronous
  • tasks can be prioritized, work can be paused, discarded and so on.
  • internal function like 【beginWork()】 and 【completeWork()】 are being called
🥈 commit phase

the second phase is the commit phase and during the phase, it is the function 【commitWork】 that is being called

  • 【commitWork()】is being called
  • this phase is synchronousand cannot be interrupted

Fiber properties

  • Fiber always has a 1-1 relationship with 'something'( sth => eg: component instance, DOM node, etc.
  • type of 'sth' is stored inside the tag property( number from 0 to 24
  • the stateNode property holds the reference
tag property

Arent' Fibers really similar to React Elements?

That is partially true, because they are in fact very often created from React Elements.

  • Fibers are often created from React elements
  • They even share the 【type】 and 【key】 properties
  • White React Elements are re-created every time, Fibers are being reused as often as possible
  • Most Fibers are created during the inital mount. But again, after that, they are mostly being reused

The important differnce between Fibers and React Elements is that React Elements are re-created every time.
One thing to be clear about: React Elements and React Fibers have to be created at some point and that point is the initial mount.

source code about the creation of Fiber
  • createFiberFromElement()
  • createFiberFromFragment()
  • createFiberFromText()
    and so on...

Fiber properties

The next import ones are child, sibling, and return

  • child, sibling, return (Fiber relationships)
  • Fibers also from a tree(same as React Elements also form a tree)
  • single child - reference to the first child

Summarize what we konw

  • there is a tree of connected Fibers
  • they represent React elements and other things as well
  • Each Fiber = unit of work
  • Fibers are processed in two phases
  • the first (render) phase is asynchronous
  • the second (commit) phase is synchronous (the commit phase work is performed synchronously and is reflected on screen.

This is a good conceptual overview(概念性概述) of what is going on, but we still have no idea what exactly is work?

What exactly is Work ? (unit of "work")

  • state change -> work
  • lifecycle function -> work
  • changes in the DOM -> work
Perform work
  • work can be handled directly or scheduled for the future
  • using 【time slicing】, work can be split into chunks
  • high priority work like animations can be scheduled in such a way they are handled ASAP
  • low priority work like network requests can be delayed

When handle work?

  • requestAnimationFrame() ===> schedules a high priority function
  • requestIdelCallback() ===> schedules a low priority function

🌲🌲🌲 Fiber Tree

double buffering, write to a separate invisible buffer and when completed, they just swapped the buffers
during the commit phast, React does the same thing with the Fiber trees

Swapping Tree is Not Enough

during the render phase, React does all sorts of asynchronous things

  • React works asynchronously during the render phase
  • Work has to be done during the commit phast as well
  • What type of work ? eg: Lifecycle methods / DOM Changes

logically, changes to the DOM or lifecycle methods like componentDidMount() cannot be executed during the render phase

The result of the render phase is not only a tree of Fibers but also a list Effects

What is An effect ?

  • mutating the DOM / calling specific lifecycle methods
  • Effects heavily depend of the Fiber
  • Host component(div) -> updating the DOM
  • Class component -> calling lifecycle method
  • Lifecycle methods like render() and shouldComponentUpdate() are part of the render phase

Effect is an activity like mutating the DOM or calling particular lifecycle methods ( side effects)

🍟🍟🍟 Effects are tracked using properties like firstEffect, lastEffect, nextEffect, etc

How are Effects Applied?
  • During the commit phast, React goes through all Effects and applies them to component instances.
  • This results in changes visible to the user
  • React done all of that in a single pass

Effects for host components like div can be adding, updating, or removing elements in the DOM
They can affect other components and once again, they cannot be executed during rendering

Fibers = units of work processed by functions like 【begingWork()】 and 【completeWork()】

☘️ React first steps into a Fiber by calling beginWork() and keeps stepping in until it reaches a Fiber without children
☘️ React then completes that Fiber by calling completeWork()

beginWork() = going downwards
completeWork() = going upwards

How React processes A Fiber Tree?

  1. start working on a1 and notices a1 has child ===> move to b1
  2. b1 doesn't have a child ===> complete b1
  3. b1 has sibling ===> move to b2
  4. b2 has child ===> move to c1
  5. c1 has child ===> move to d1
  6. d1 doesn't have a child ===> complete d1
  7. d1 has sibling ===> move to d2
  8. d2 doesn't have a child ===> complete d2
  9. d2 has no child or sibling ===> complete c1
  10. complete c1 ===> complete b2
  11. b2 has sibling ===> move to b3
  12. b3 doesn't have a child or sibling ===> complete b3
  13. b3 doesn't have a child or sibling ===> move to root Node and complete root Node

☘️
After React completes the final Fiber, also known as the root Fiber, commitWork() is called, Effect
are applied and changes are flushed to the DOM
This is done using a while loop(workLoop), but the important thing is that all of this isn't recursive

ALternate property

Two Fiber trees ---> 【current fiber tree】 & 【workInProgress tree】

  • points to the Fiber on the other end of the pair(详细了解一下
  • helps Fibers to be reused

React Fiber Usage

  • Error boundaries ( catch blocks of components | getDerivedStateFromError() | componentDidCatch()
  • Suspense and Concurrent Mode
posted @   Felix_Openmind  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
历史上的今天:
2023-01-04 可视化Echart模板component
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}
点击右上角即可分享
微信分享提示