Kyle Mo
Become a better React Developer
(Breakout Rooms 5 Mins)
1. 第一個印出 false,第二個印出 true
2. 第一個印出 true,第二個印出 false
3. 兩個都印出 false
4. 兩個都印出 true
const [isLoading, setIsLoading] = useState(false);
const handleClick = () => {
console.log('isLoading: ',isLoading)
setIsLoading(true)
console.log('isLoading: ',isLoading)
}
兩次印出的 count 分別為多少?count state 的值實際上是多少?
const [count, setCount] = useState(0);
const handleClick = () => {
console.log('count: ',count)
setCount(count + 10)
setCount(count + 10)
setCount(count + 10)
console.log('count: ',count)
}
A: 0, 0, 10
const [count, setCount] = useState(0);
const handleClick = () => {
console.log('count: ',count)
setCount(prev => prev + 10)
setCount(prev => prev + 10)
setCount(prev => prev + 10)
console.log('count: ',count)
}
兩次印出的 count 分別為多少?count state 的值實際上是多少?
A: 0, 0, 30
文件物件模型(Document Object Model, DOM)是 HTML、XML 和 SVG 文件的程式介面。它提供了一個文件(樹)的結構化表示法,並定義讓程式可以存取並改變文件架構、風格和內容的方法。(From MDN)
Outline
What is React Fiber ?
React Reconciler
Overview of fiber reconciler algorithm
What Fiber brings for the future ?
Why Fiber use linked list to walk component tree?
What is React Fiber ?
{
stateNode: new ClickCounter,
type: ClickCounter,
alternate: null,
key: null,
updateQueue: null,
memoizedState: {count: 0},
pendingProps: {},
memoizedProps: {},
tag: 1,
effectTag: 0,
nextEffect: null
}
Animation
Responsiveness
&
What can it do ?
JSX -> React Element -> Fiber Node
What we know about fiber for now ?
There is tree of connected fibers
They represent react element and other things as well
Fibers are processed in two phase
Fiber = unit of work
- Render Phase
- Commit Phase
Synchronous
Asynchronous
React Reconciliation
為什麼原來的 Diffing 要 O(n³) ?
具體來說,想像我們有兩棵樹:舊樹和新樹。我們要遍歷舊樹中的每個節點,並與新樹中的每個節點進行比較。這本身就是 O(n²)。但是,當我們考慮到可能的子節點和子樹的變化時,我們必須再次進行類似的遍歷,導致 O(n³) 的算法複雜度。
A
├── B
│ ├── D
│ └── E
└── C
A
├── B
│ ├── D
│ └── F
└── C
Before Fiber
After Fiber
Reconciler
Renderer
Scheduler
Reconciler
Renderer
- Reconciliation 是實作在 React Core 裡,不同 renderer 共用 Diff 演算法
- Renderer 代表 ReactDOM, React Native,各自負責渲染元件到畫面上
Old Reconciler - Stack (< React 16)
- Work synchronous
- Work recursively, like call stack
- Had to work until the stack is empty
Fiber
Reconciler
New Reconciler -
Fiber Tree
Virtual DOM ->
Why Fiber use linked list to walk component tree?
node1
node2
node3
What does browser do in 1 frame ?
Render Phase
Commit Phase
React walk the fiber tree and....
What is the problem ?
React is going to walk the entire tree of components synchronously and perform work for each component
It may run over 16 ms
Will cause frames to drop causing stuttering visual effects.
rIC, rAF To The Rescue
requestIdleCallback((deadline) => {
//while we have time, perform work for a part of the components tree
while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && nextComponent) {
nextComponent = performWork(nextComponent);
}
});
rAF: high priority task (animation)
rIC: low priority task (network request)
Well...we have big trouble....the work can not broke into smaller chunks
React just keeps iterating until it processed all components and the stack is empty.
synchronous
walk(a1);
function walk(instance) {
doWork(instance);
const children = instance.render();
children.forEach(walk);
}
function doWork(o) {
console.log(o.name);
}
Stack -> Linked List
Uses a linked list tree traversal algorithm. It makes it possible to pause the traversal and stop the stack from growing!
- one child
- one sibling
- one return
How React Process A Fiber Tree ?
A
B-1
B-1
B-2
B-3
C-1
D-1
D-2
= begin
= complete
1. DFS
2. child -> 自身 -> sibling
Stack doesn’t grow as we walk down the tree
Overview of fiber reconciler algorithm
Render Phase
Commit Phase
Pre-Required Knowledges
- Current & Work In Progress Tree
alternate
Side Effects
- mutating the DOM
- calling lifecycle methods
Render
Commit
Each fiber node can have effects associated with it. They are encoded in the effectTag field.
So effects in Fiber basically define the work that needs to be done for instances after updates have been processed.
Synchronous
Effects List
Run Through The Process
1. JSX -> React Elements (tree)-> Fiber Nodes (tree)
2. state change , re-render : JSX -> React Elements (tree)-> Fiber Nodes marked with side effect (WorkInProgress tree)
Asynchronous Render Phase
Some lifecycle methods run in render phase, can't operate DOM
3. Turn WorkInProgress tree to current
Render Phase -> Tree of fibers + List of effects
How effects applied ?
- commit phase, React go through the effect list and applied them to component instance
- synchronously, user can see these changes
Some lifecycle methods run in commit phase
What Fiber Brings For The Future ?
Concurrent Mode || Concurrent Features
Suspense
Use web worker to parallelize works
Use WebAssembly
Recap
- React use fiber architecture to refactor since v16
- Fiber represent 'unit of work'
- Not all for performance, it makes React smarter
- Two phase of Fiber Reconciler: render (async) -> commit (sync)
- From stack to linked list
- Is the base of many React's future features