React Fiber: A Dive into Understanding What is it and How it Works?

React Fiber, as we speak, is the most recently introduced reconciliation algorithm, which is nothing but the implementation of the previous algorithm which served till React version 15.

After the introduction of React 16, the community was brought to light by the much faster and more agile reconciler known as “Fiber”. We will be covering the following points which will provide us with a much deeper understanding of React Fiber.

Introduction to React Fiber

The name “Fiber” was coined from React’s architecture and derived from ‘fiber’ which is a depiction of a node inside the DOM tree. Some of the reasons to justify why React Fiber was imperative include:

✔️ It gives us the ability to break down our work into various chunks.
✔️ It also provides the power to assign priority for every unit of work that demands completion.

✔️ It helps in providing a much-sharpened rendering of UI gestures/animations for user interactions.

Before diving much deeper into the technicalities of Fiber and understanding its true powers, let us first understand the old reconciler.

What is the React Reconciliation Algorithm and How Does it Work?

While learning React, the very first thing we learn is how the UI is rendered onto the screen for the first time or every time something is updated in the UI. Each time when we develop a new React application and the UI is rendered onto the screen for the first time, React builds a tree-like structure of nodes where each node is represented as a React element.

A clone of the rendered DOM tree is created by React(under the hood), known as the virtual DOM. Every time a component’s state or props gets updated, React makes a decision on updating the DOM tree by comparing the newly returned element with the previous one.

During the comparison, if the elements are found to be different in both the trees(previously rendered and newly created), then only the DOM is updated and the cumulative changes are passed on to the renderer. This complete process is referred to as “Reconciliation”.

The two primary components responsible for rendering element onto the DOM includes-

🔸 Reconciler: This component is primarily responsible for the computation part and for notifying React of the parts that need updating.
🔸 Renderer: This component takes the computed part and updates the rendered tree which ultimately is displayed on the user screen.

Let us understand how React converts the components into a tree structure of nodes by considering this basic example:

import { React, useState } from "react";

const App = () => {
const [count, setCount] = useState(1);
const handleClick = () => {
setCount(count => {
return count + 1;
});
};

return (
<React.Fragment>
<button onClick={handleClick}>Increment</button>
<p>Count Value: {count}</p>
</React.Fragment>
);
};

export default App;

A number of activities are performed during the “reconciliation” process including the high-level operations performed by React during the first render along with managing the state change.

For instance, in the above example, some of the activities that React takes care of are:

🔹Updating the value of the count property in the App component
🔹 Handling props for the “p” element on every updation
🔹 Retrieval and comparison of the children of the App component

These activities collectively are cited as “work” in Fiber architecture. The type of work majorly depends on the React element type defined by the first parameter to the “createElement” function. This function is used inside the render method to create an element.

🅰️ The Component first goes through the JSX compiler to convert the element into React elements.
🅱️ The “React.createElement” function then creates the nodes in the following manner.

react fiber create element

Why did the Need for New Architecture Arise?

The previous algorithm came with certain limitations due to which Fiber reconciler had to be brought into action.

One such limitation was the immediate enforcement of any update that was made to the component due to the recursive nature of the algorithm. As the DOM tree gets larger and bigger in size, it becomes extremely difficult and costly to manage these updates and can ultimately lead to dropped frames.

Another issue that came with it was, that as Javascript is single-threaded in nature so all the tasks including UI updates, managing user actions, API calls, and handling animations and gestures were all managed by a single thread. When the first reconciliation phase is triggered, the current tree and updated tree(with all new updates) get rendered.

The reconciler detects the differences between the two trees within a single pass in a synchronous manner, thus preventing the main thread from taking care of other high-priority tasks.

To overcome these limitations, the Meta(Facebook) team came up with the new React Fiber Architecture enhanced and much smoother Fiber Reconciler in its React 16 update.

The Purpose Behind Introducing React Fiber

💠 Oversight Over Work Priority: As Fiber provides us with the feature of incremental rendering, it allows us to divide our work into smaller chunks and dispense it into multiple frames, allowing us to have complete control over the priority of work.

💠 Enhanced Performance: The sole purpose of introducing Fiber was to improve/enhance the performance of extremely large and complex React apps. Fiber provides React the ability to break the limits of the call stack which allows it to halt and resume rendering work when required.

💠 A Much Smoother Experience: React fiber promises a much smoother experience by letting React fine-tune the rendering part, responsible for ensuring that the most recurrent and paramount use cases are taken care of at the earliest.

Hire React Developers to Build Innovative Web and Mobile Applications

The Architecture of Fiber Along with the Phases Involved

Fiber’s architecture comprises two major phases, the first one being the “reconciliation” phase which is mostly referred to as the “render” phase in the React source code, and the second one which is referred to as the “commit” phase.

🟢 Phase 1: Render

This phase is primarily responsible for walking through the tree of components and taking care of multiple activities including calling lifecycle hooks, alteration of props and state, retrieving “children” from components, and figuring out the DOM updates that need to be performed.

Basically, if React goes through the tree of components in a synchronous manner and performs some work on each of them, it may run over 16ms for an application code to execute the logic built which will ultimately cause the frames to drop resulting in stuttering visual effects.

In order to get around this issue, Fiber makes use of the “requestIdleCallback” function which is used to queue a function to be called during a browser’s idle period. Let us assume that if we put all the activities that will be performed on a component in a function like “executeTask” and use “requestIdleCallback” to schedule the work, our code snippet would look like this:

requestIdleCallback(deadline => {
// While time is remaining, perform work for other part of the components tree
while (
(deadline.timeRemaining() > 0 || deadline.didTimeout) &&
nextComponent
) {
nextComponent = performWork(nextComponent);
}
});

Reacts performs the work on one component and then returns the reference to the next component that needs to be processed. Once the list is entirely computed, React schedules the changes that are to be executed in the next phase.

🟢 Phase 2: Commit

Of all the scheduled changes that come out of the reconciliation phase, React can choose to render a specific set of changes. After the commitment is done, React notifies the DOM to render the changes that were found during the reconciliation phase, and since all these changes are visible to the user, therefore this phase needs to be completed in a single call.

Key Benefits of React Fiber

✔️ React Fiber allows us to handle runtime errors in a much cleaner fashion by setting up error boundaries which allow us to show an alternative screen in case something goes wrong.
✔️ It enhances the performance of our system by being able to split the limits of the call stack and allowing React to halt and resume rendering work when required.
✔️ It also provides us with support for returning some new render types including fragments and strings.
✔️ It allows us to create certain advanced elements using animations, gestures, layouts, and much more.

coma

Conclusion

Through this blog, we understood how React Fiber reconciler makes things extra easy by splitting the work into several units, prioritizing each work, and also making it possible to pause, resume and abort any unit of work. In a fiber tree, it is the responsibility of the individual node to keep track of what is needed to make the above things possible.

Keep Reading

Keep Reading

Leave your competitors behind! Become an EPIC integration pro, and boost your team's efficiency.

Register Here
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?