React Fiber

Learn via video courses
Topics Covered

Overview

We are aware that ReactDOM constructs the application's DOM tree and renders it on the screen. But how does React create the DOM tree in reality? When the app's state changes, how does it update the tree?

In this article, we'll discuss React Fiber, how the DOM tree was constructed up until React v15.0.0, its drawbacks, and how the new model introduced in React v16.0.0 and later versions addresses these issues. This article will go over a variety of ideas that are merely implementation details for internal use and are not strictly necessary for front-end development using React.

Prerequisites

To fully understand and use React Fiber, it is important to have a good understanding of the following concepts:

  • Virtual DOM:
    The Virtual DOM is an abstract representation of the actual DOM in a React application. React uses the Virtual DOM to render the UI efficiently.
  • Reconciliation:
    Reconciliation is the process by which React updates the Virtual DOM to reflect changes in the state of a component. In React Fiber, this process is optimized for better performance.
  • Components:
    Components are the building blocks of a React application. They can be either stateful or stateless, and they define the structure and behavior of the UI.
  • State and Props:
    Components in React have state and props, which are used to manage the data and behavior of a component. Understanding how state and props work is crucial to using React effectively.
  • JSX:
    JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. It is used in React to define the structure of the UI.
  • Scheduling:
    In React Fiber, scheduling refers to the process of determining when and how to update the components in a React application. With asynchronous rendering, React Fiber can schedule updates to the components in a way that balances the need for smooth animation and efficient updates.
  • Lifecycle Methods:
    React components have lifecycle methods, which are methods that are called at specific points in the life of a component. Understanding these methods is important for controlling the behavior of a component.
  • Asynchronous rendering:
    React Fiber allows for asynchronous rendering, which means that the rendering of a component can be split into multiple chunks and processed in the background. This is important for improving the performance of React applications, especially in areas such as animation.

What is React Fiber?

React Fiber is a new reconciler that was introduced in React 16.0. A reconciler is a component responsible for updating the virtual DOM and applying changes to the actual DOM. React Fiber is a complete rewrite of React's previous reconciler and is aimed at improving the performance of React applications, especially in areas such as animation and layout.

React Fiber works by breaking down the rendering process into smaller, more manageable chunks and allowing React to schedule and process these chunks as needed, in a way that balances the need for smooth animation and efficient updates.

React Fiber uses a priority-based scheduling system, where updates are divided into different priority levels, such as high, low, and deferred. Higher priority updates, such as user interactions or animations, are processed first, while lower priority updates, such as rendering updates for background tasks, are processed later.

React Fiber also can pause, abort, and resume work on a component, allowing for greater control over the rendering process and ensuring that updates are performed smoothly and efficiently. This is particularly useful for complex animations or other tasks that require a lot of CPU time, as React Fiber can allocate resources accordingly to ensure the best possible performance.

React Fiber is a major step forward for React, providing a more powerful and flexible reconciler that enables React applications to deliver better performance and a more engaging user experience.

Features of React Fiber

React Fiber includes several features that improve the performance and flexibility of React applications. Some of the key features of React Fiber include:

  • Asynchronous rendering:
    React Fiber allows for asynchronous rendering, which means that the rendering of a component can be split into multiple chunks and processed in the background. This is important for improving the performance of React applications, especially in areas such as animation.
  • Priority-based scheduling:
    React Fiber uses a priority-based scheduling system, where updates are divided into different priority levels, such as high, low, and deferred. This allows React to efficiently allocate resources and optimize the rendering process, improving the overall performance of the application.
  • Improved handling of server-side rendering:
    React Fiber includes improvements to the handling of server-side rendering, making it easier to use React in a server-side environment and improving the performance of server-side rendering.
  • Better error handling:
    React Fiber includes improved error handling, making it easier to debug and fix issues in React applications.
  • Intuitive and flexible API for defining animations:
    React Fiber includes a more intuitive and flexible API for defining animations and other complex UI interactions, making it easier to create engaging and dynamic user interfaces.
  • Fine-grained updates:
    React Fiber allows for fine-grained updates, which means that React can update individual parts of a component's UI, rather than having to re-render the entire component. This results in more efficient updates and improved performance.
  • Improved memory usage:
    React Fiber includes improvements to memory usage, making it possible to render larger and more complex applications while using less memory.
  • Better support for progressive loading:
    React Fiber includes improved support for progressive loading, making it easier to create applications that load quickly and provide a smooth user experience.

Structure of React Fiber

React Fiber has a hierarchical structure that allows for efficient and flexible rendering of components. At a high level, the structure of React Fiber can be broken down into the following parts:

  • Work units:
    React Fiber uses work units to represent the work that needs to be performed during rendering. Work units can represent individual components or parts of components, and they are used to keep track of the progress of rendering.
  • Fiber nodes:
    Each work unit is represented by a fiber node in the fiber tree. Fiber nodes are essentially a data structure that stores information about a component and its state, including the type of component, its props, and its current render output.
  • Fiber tree:
    The fiber tree is a hierarchical representation of the components in a React application. The fiber tree is created during the render process, and it is used to keep track of the work that needs to be performed and the state of the components.
  • Scheduler:
    The scheduler is responsible for deciding when and how to process the work units in the fiber tree. The scheduler uses a priority-based system to determine which work units should be processed first, and it can pause, abort, or resume work on a component as needed.
  • Renderer:
    The renderer is responsible for actually performing the render and updating the user interface. The renderer works in conjunction with the scheduler to perform the render smoothly and efficiently, using the information stored in the fiber tree.

This hierarchical structure allows React Fiber to efficiently manage the rendering process and perform updates in a way that balances the need for smooth animation and efficient updates. By breaking down the rendering process into smaller, more manageable parts, React Fiber enables React applications to deliver better performance and a more engaging user experience.

The following lines of codes demonstrate the structure of react fiber:

Explanation:

In this example, the Counter component is a simple React component that displays a count and a button to increment the count. The useState hook is used to manage the state of the component, which is the current count.

When this component is rendered, React creates a fiber node in the fiber tree to represent the work that needs to be performed. The fiber node stores information about the component, such as its type, its props, and its current render output.

The scheduler then determines when and how to process the work for this fiber node. In this case, the work is to render the Counter component and update the user interface with the current count.

Finally, the renderer performs the render and updates the user interface. In this example, the renderer updates the text of the p element to display the current count and updates the user interface to show the updated count.

This demonstrates the basic structure of React Fiber, where the fiber tree, scheduler, and renderer work together to perform the render and update the user interface efficiently and flexibly.

How Does React Fiber Work?

React Fiber is a reimplementation of React's core algorithm. It was introduced in React 16.0 to improve the perceived performance of React applications by breaking the render process into smaller, more manageable chunks that can be spread out over multiple frames.

React Fiber is based on a concept called "reconciliation". This is the process that React uses to compare the desired state of a component tree with its current state and make updates as needed.

React Fiber consists of several phases:

  • Initial Render Phase:
    This is the phase where React builds the initial tree of components to be rendered.
  • Commit Phase:
    It is the function commitWork() that is being called at this time. This stage cannot be stopped because it is synchronous. When handling a fiber, React either completes the task immediately or plans it for later. React may break up work into smaller pieces using a technique called time-slicing. React may schedule tasks with a high priority, like animation, so that they are completed as fast as feasible. On the other hand, if a task has a low priority, like a network request, React can simply delay it for however long is necessary. It accomplishes this via the functions requestAnimationFrame() and requestIdleCallback(). request AnimationFrame():
    Schedule high-priority functions to be called on the following animation frame. requestIdleCallback():
    enables the calling of a low-priority function at an idle time.
  • Rendering Phase:
    This stage is asynchronous. React performs a variety of asynchronous tasks during this stage that are hidden from the user. The extra options that come with it being asynchronous are those we just mentioned in passing. Tasks can be sorted in React. Work on some projects may be put on hold, abandoned, etc. As I mentioned before, React processes every fiber, which serves as the unit of labor, during this step. Internal functions like beginWork() and completeWork() is called at this stage.

React’s Stack Reconciler

The React Stack Reconciler is a core component of the React JavaScript library that manages the updates and rendering of components in response to changes in state or props. It is responsible for diffing the virtual DOM tree, determining which components need to be updated, and updating the actual DOM accordingly.

The Stack Reconciler is designed to be efficient and performant, minimizing the number of DOM operations required to update the tree, and taking advantage of batching and reuse where possible. It uses a process called reconciliation to determine what changes need to be made and then makes the necessary updates to the DOM.

The Stack Reconciler is an important part of React's architecture and is one of the key factors that make React fast and scalable. It's a complex system, but it abstracts away the underlying implementation details, allowing developers to focus on building their applications without having to worry about low-level DOM operations.

Recursion in React

React Fiber is a complete overhaul of the React core algorithm and is designed to be backward compatible with previous versions of React. One aspect of Fiber that differs from previous versions of React is its handling of recursion.

React Fiber uses a concept called "recursion" during the commit and rendering phases. Recursion in React Fiber works similarly to recursion in other programming languages. It involves a function calling itself repeatedly until a certain condition is met. In React, a recursive component calls itself, possibly with different props.

React Fiber handles recursion by breaking the work into smaller chunks and prioritizing the most critical updates first. This means that the deepest parts of the recursion will be processed first, reducing the chances of a stack overflow.

It's important to keep in mind that too much recursion can still cause performance issues, especially in complex UI scenarios. To avoid this, it's a good idea to use a maximum recursion depth or include a check for an ending condition that will stop the recursion.

Some Tips While Using React Fiber

React Fiber is the latest version of React's reconciliation algorithm and it's optimized for high performance and better handling of complex UI updates. Here are some tips that can help you when using React Fiber:

  • Use React.memo to memoize functional components:
    React.memo is a higher-order component that lets you optimize functional components. React.memo checks if the props have changed and skips rendering if they have not changed.
  • Use React.lazy to load components lazily:
    React.lazy allows you to load components lazily when they are needed, rather than loading them all at once when your app starts.
  • Split components into smaller pieces:
    Splitting components into smaller, more focused components can help with performance and also make your code more maintainable.
  • Use useEffect hook for side effects:
    The useEffect hook lets you run some code after rendering. It’s a great way to perform side effects like network requests or updating the DOM.
  • Use requestAnimationFrame to schedule updates:
    requestAnimationFrame is a way to schedule updates to the DOM to run before the next frame. This can help ensure that updates run smoothly and don’t cause dropped frames.
  • Be mindful of component state updates:
    State updates can cause re-renders, which can negatively impact performance. Minimize unnecessary state updates and try to batch state updates when possible.
  • Use the profiler:
    The React profiler is a tool that helps you identify performance bottlenecks in your application. Use it to find and fix performance issues.
  • Use concurrent mode:
    React Fiber introduces the concept of concurrent mode, which allows for multiple updates to be processed in parallel. This can help to improve the performance of your application, especially when dealing with complex UI updates.

Conclusion

  • React Fiber is a new and improved rendering algorithm for React, designed to improve the performance and responsiveness of React applications.
  • React Fiber breaks down the rendering process into smaller, more manageable parts, allowing for more efficient and flexible updates to the user interface.
  • React Fiber uses work units to represent the work that needs to be performed during rendering, and a fiber tree to keep track of the work and the state of the components.
  • The scheduler is responsible for deciding when and how to process the work units in the fiber tree, using a priority-based system to balance the need for smooth animation and efficient updates.
  • The renderer performs the render and updates the user interface, using the information stored in the fiber tree to perform the render smoothly and efficiently.
  • React Fiber allows for more efficient rendering by allowing the scheduler to pause and resume work on a component as needed, and more flexible updates by allowing the scheduler to split work into smaller units and schedule them in a way that balances the need for smooth animation and efficient updates.
  • React Fiber results in smoother and more responsive user interfaces, especially in complex and highly dynamic applications.
  • Overall, React Fiber is a significant improvement over the previous rendering algorithm in React, designed to improve the performance and responsiveness of React applications.