React Fiber Algorithm
In this article, we will learn about React Fiber — the core algorithm behind React. React Fiber is the new reconciliation algorithm in React 16.
You’ve most likely heard of the virtualDOM from React 15. It’s the old reconciler algorithm (also known as the Stack Reconciler) because it uses stack internally. The same reconciler is shared with different renderers like DOM, Native, and Android view. So, calling it virtualDOM may lead to confusion.
React Fiber is a completely backward-compatible rewrite of the old reconciler. This new reconciliation algorithm from React is called Fiber Reconciler. The name comes from fiber, which it uses to represent the node of the DOM tree.
The reconciler also allows you to divide the work into multiple chunks and divide the rendering work over multiple frames. It also adds the ability to define the priority for each unit of work and pause, reuse, and abort the work.
Some other features of React include returning multiple elements from a render function, supporting better error handling and portals.
While computing new rendering updates, React refers back to the main thread multiple times. As a result, high-priority work can be jumped over low-priority work. React has priorities defined internally for each update.
How does React Fiber work?
Next, we will see how the React Fiber creates the linked list tree and what it does when there is an update.
Before that, let’s explain what the current tree and workInProgress tree are in the above example and how the tree migration takes place.
The tree, which is currently flushed to render the UI, is called current. It’s one that was used to render the current UI. Whenever there is an update, Fiber builds a workInProgress tree, which is created from the updated data from the React elements. React performs work on this workInProgress tree and uses this updated tree for the next render. Once this workInProgress tree is rendered on the UI, it becomes the current tree.
Fiber tree traversal happens like this
- Start: Fiber starts traversal from the topmost React element and creates a fiber node for it.
- Child: Then, it goes to the child element and creates a fiber node for this element. This continues until the leaf element is reached.
- Sibling: Now, it checks for the sibling element if there is any. If there is any sibling, it traverses the sibling subtree until the leaf element of the sibling.
- Return: If there is no sibling, then it returns to the parent.