A journey through ReactDOM.render — An explanation of how React manages the DOM and state

An overview of the fiber architecture used in React, and how it is used to manage the DOM

ReactDOM is an object which exposes a number of top-level APIs to interact with the browser DOM. According to the docs, it provides ‘DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside of the React model if you need to’. One of those methods is render() .

Some background notes

Before going further, it is worth having a general understanding of React’s internal workings. In React 15, updates were done in a synchronous manner. This created the risk of updates running slower than the 16ms (1000 milliseconds / 60 frames per second) needed for computation, causing janky UIs. React 16 introduced fiber, a re-write of React’s reconciliation algorithm which allowed updates to be scheduled asynchronously and be prioritized. This was done by re-implementing the browser’s built-in call stack. Doing so made it possible to interrupt the call stack and manually manipulate the stack frame in a way specially tailored for React components.

At the core of this re-write is a data structure called a fiber, which is an object that is mutable and holds component state and a DOM representation. It can also be thought of as a virtual stack frame. Fiber’s architecture is split into two phases: reconciliation/render and commit. Over the course of this article we will touch upon some of its aspects but more extensive explanations can be found here:

The journey begins

ReactDOM.render() actually wraps another function and invokes it with two additional arguments, so its declaration is simple. Below is the wrapped function:

The first thing React does is create the fiber tree for our application. Without this, it cannot handle any user updates or events. The tree is created by calling legacyCreateRootFromDOMContainer , which returns the following object:

This is called a fiber root object. Every React app has one or more DOM elements that act as containers and for each of these containers, this object is created. It is on this object we find a reference to our fiber tree via the current property, and its value is:

This is a fiber node and it is found at the root of every React fiber tree (this is the function which creates this object). This node is actually a special type of fiber node called a HostRoot node and it acts as a parent for the uppermost component in our application. We know it is a HostRoot node because the value of its tag property is 3 (you can find the full list of fiber node types here). Notice how at this stage, a lot of the properties, especially child , are null . We will come back to this later.

After creating the tree, React checks if we provided a callback as the third argument of the render call. If so, it grabs a reference to the root component instance of our application (in our case, it is the <h1> element) and then makes sure our callback will be called on this instance later on.

Into the thick of it

All the stuff that has happened prior to this point is preparation for the work that will render our application on screen. So far, we have a tree but it does not resemble our UI. This problem is solved with the following code:

Root is an object with only one property (the property _internalRoot which holds a reference to the root fiber object). It was created by calling new on the ReactRoot function, so if you look up its internal [[Prototype]] chain you will find the following method:

Remember our HostRoot fiber node earlier with all the null values? In the function above, we can access it via root.current . After updateContainer() has finished its work, this is what it looks like:

And the value in the child property is now a fiber node for the <h1> element:

As you can see, the fiber tree now reflects the UI we want to be rendered. How did that happen? Below is a summary of the steps which took place in order to get us to this stage:

Schedule the updates

React has an internal scheduler which it uses for handling co-operative scheduling in the browser environment. This package includes a polyfill for window.requestIdleCallback , which is at the heart of how React reconciles UI updates. During the process each fiber node is given an expiration time. This is a value which represents a time in the future the work (the name given to all the activities which happen during reconciliation) being done should be completed.

This calculation involves checking if there is any pending work with a higher priority as well as the nature of the work currently going on. In our case, it is a synchronous update but in other scenarios it could be interactive or asynchronous. Examples of low priority updates include network responses or clicking a button to change colours. High priority updates include user input and animations.

Create an update queue

In our example, we only have one fiber tree and since it has no update queue, one has to be created and assigned to the updateQueue property. This queue is created with the createUpdateQueue function and it takes the fiber node's memoizedState as its argument. Memoized state refers to the state used to create the node's output. The queue is a linked list of prioritised updates and like fiber trees, it also comes in pairs. The current queue represents the visible state of the UI.

Create the work-in-progress tree and do work on it

When the work is actually being performed, React checks its internal stack to determine whether it is starting with a fresh stack or resuming previously yielded work. Soon after this check it uses a technique known as double buffering to create the workInProgress tree. React works with two fiber trees — one named current which holds the current state of the UI and another named workInProgress which reflects the future state. Every node in the current tree has a corresponding node in the workInProgress tree created from data during render.

Once the workInProgress is rendered on the screen, it becomes the new current tree. The workInProgress tree also has an update queue but it can be mutated and processed asynchronously before being rendered.

DOM element creation

The fiber node for the <h1> element is created during the work on the workInProgress tree. A few calls later, this function uses the DOM API to create our <h1> element, which so far has been a React element object. When the application has rendered, you can access the element by typing document.querySelector('h1') . If you check its properties, you will find one beginning with __reactInternalInstance$ . This property holds a reference to the element's fiber node. React also assigns the element's text content and then later appends it to our root DOM element. By the time its appended, React has already entered its commit phase.

You can view the fiber node for any HTML element created in React by looking at the value of this property

And that is all there is to it

In our example we have rendered the most basic of UIs but React has done a lot of work to prepare and display it. Like most frameworks created for building complex applications, it does this work to prepare for all the eventualities associated with such a task. And with the example application being static, we have not touched on any of the code involved in state updates, lifecycle hooks and the rest of it.

As this is my first time doing a deep dive on React, I am sure I have missed things out or incorrectly explained others, so please, leave your feedback below!