DEV Community

Quan Phan
Quan Phan

Posted on • Edited on

React Fiber tree

Context

This post is part of my post series that complements the "Build your own React" tutorial by Rodrigo Pombo.

In this post...

In step 4, Rodrigo introduced the Fiber architecture. However, he didn't relate Fiber to the bigger picture of React. This post will review what Fiber is, what its purpose is, and how this concept relates to Virtual DOM.

What is Fiber?

Fiber tree is a tree data structure, where each node is a Fiber. A Fiber is an object that has the following properties:

interface DidactElementProps {
    [key: string]: any;
    children: DidactElement[];
}

interface DidactElement {
    type: string | Function;
    props: DidactElementProps;
}

interface Fiber extends DidactElement {
    parent: Fiber;
    sibling: Fiber;
    child: Fiber;
    dom: HTMLElement | Text;
    alternate: Fiber;
    effectTag: string;
}
Enter fullscreen mode Exit fullscreen mode

What can make Fiber confusing is the fact that the object encompasses so much information. Let's break it down:

  • (Information of) the virtual DOM: type and props
  • The actual DOM node: dom
  • Its connection to the tree: parent, child, sibling
  • The corresponding fiber in the previous render: alternate
  • Message to the commit phase on what to do with this Fiber: effectTag (update/delete/insert into the DOM)

A Fiber node represents either a DOM node (h1, div, p, etc.) or a function that corresponds to a functional component.

Purpose of Fiber tree

It enables us to break down the rendering phase into small units of work, each of which corresponds to a Fiber in the tree. The browser decides the number of work units/fibers it works on before it has to leave the rendering and come back later because it has a higher priority task awaits.

Fiber and Virtual DOM

In Rodrigo's tutorial, the Fiber tree "acts" as a virtual DOM.

In the first code snippet:

1 | const element = <h1 title="foo">Hello</h1>
2 | const container = document.getElementById("root")
3 | ReactDOM.render(element, container)
Enter fullscreen mode Exit fullscreen mode

The first line creates the actual virtual DOM, which is passed into the render function. Down the line, in reconcileChildren (in step 5), the type and props of each node in the virtual DOM are deconstructed and initiated as the type and props of a fiber.

Mentally, we can think of it as the Fiber tree is a physical representation of the virtual DOM or the Fiber tree acts as a virtual DOM.

Deeper read

https://github.com/acdlite/react-fiber-architecture

Top comments (0)