The Fiber Reconciler
Relevant source files
The following files were used as context for generating this wiki page:
- packages/react-reconciler/README.md
- packages/react-reconciler/index.js
- packages/react-reconciler/src/ReactChildFiber.js
- packages/react-devtools-shared/src/backend/fiber/renderer.js
- packages/react-reconciler/src/tests/ReactIncremental-test.js
- fixtures/fiber-debugger/src/describeFibers.js
- packages/react-dom/src/tests/ReactDOMFiber-test.js
The react-reconciler package is an experimental module that provides the core reconciliation algorithm for React. It is designed to be decoupled from any specific rendering environment, allowing developers to create custom React renderers for various platforms (e.g., DOM, Canvas, Native). This is achieved through a "HostConfig" interface, which acts as a bridge between the generic reconciler logic and the platform-specific API.
The reconciler's primary data structure is the "Fiber," which represents a unit of work. This architecture, known as Fiber, enables features like incremental rendering, concurrency, and prioritization. It allows React to start, pause, and resume rendering work, making the UI more responsive. The reconciliation process is split into two main phases: a potentially interruptible "Render Phase" and a synchronous "Commit Phase".
Sources: packages/react-reconciler/README.md, packages/react-reconciler/index.js, fixtures/fiber-debugger/README.md
Core Concepts
Fiber
A Fiber is a JavaScript object that contains information about a component, its input, and its output. It is the internal representation of a React element and the primary unit of work in the reconciler. Each component instance has a corresponding Fiber node.
This diagram shows the basic structure of a Fiber node and its relationship with other Fibers.
Key properties of a Fiber object include:
| Property | Description |
|---|---|
tag | Identifies the type of the fiber (e.g., FunctionComponent, ClassComponent, HostComponent). |
key | The unique key assigned to the element to help identify it during reconciliation. |
type | The component constructor (for classes) or function (for function components). For host components, it's the tag name (e.g., 'div'). |
stateNode | The local state associated with this fiber. For host components, this is the actual instance (e.g., a DOM node). |
return | A reference to the parent Fiber. |
child | A reference to the first child Fiber. |
sibling | A reference to the next sibling Fiber. |
alternate | A reference to the fiber from the other tree (current or work-in-progress) during the render phase. This allows React to reuse nodes and avoid re-allocating memory. |
flags | A bitmask describing the side effects (e.g., Placement, Update, Deletion) that need to be performed on this fiber. |
Sources: fixtures/fiber-debugger/src/describeFibers.js, packages/react-devtools-shared/src/backend/fiber/renderer.js
HostConfig
The HostConfig is a configuration object that a custom renderer must provide. It defines how the reconciler interacts with the "host" environment. This object contains a collection of methods that React calls during the render and commit phases to create, update, and remove host instances.
There are two primary modes for a renderer, specified in the HostConfig:
- Mutation Mode: Used for platforms where the host tree is mutable (e.g., DOM). It uses methods like
appendChild,removeChild, andcommitUpdate. - Persistent Mode: Used for platforms with immutable data structures. Instead of mutating nodes, it clones the parent tree for every change.
A minimal HostConfig for a mutation-based renderer would look like this:
const HostConfig = {
// ...
supportsMutation: true,
createInstance(type, props) {
// e.g. DOM renderer returns a DOM node
},
appendChild(parent, child) {
// e.g. DOM renderer would call .appendChild() here
},
// ... and many other methods
};
const MyRenderer = Reconciler(HostConfig);
Sources: packages/react-reconciler/README.md
The Reconciliation Process
The reconciliation process is divided into two main phases: the Render Phase and the Commit Phase. This separation allows React to perform the potentially slow rendering work asynchronously without blocking the main thread.
This diagram shows the high-level flow from an update trigger to the final UI update.
Sources: packages/react-reconciler/src/tests/ReactIncremental-test.js
Render Phase
The Render Phase is asynchronous and can be paused, aborted, or resumed. During this phase, React processes Fibers, determines what changes are needed, and builds a linked list of "effects" (side-effects like DOM updates). This phase does not produce any user-visible changes.
The process involves two main steps: "begin work" and "complete work".
- Begin Work: React traverses the component tree downwards, starting from the root. For each Fiber, it diffs its previous props with the new ones and decides if it needs to update. If so, it proceeds to reconcile its children.
- Complete Work: After visiting a node and all its descendants, React "completes" the work for that node. This involves creating host instances (like DOM elements), and bubbling up the effect list from the children to the parent.
This diagram illustrates the traversal pattern of the render phase.
Child Reconciliation
A core part of the "begin work" step is reconciling the children of a Fiber. The reconcileChildFibers function implements the diffing algorithm to compare the new list of children with the previous list. The use of the key prop is crucial for this process to be efficient, as it allows React to identify insertions, deletions, and reorders.
The algorithm generally follows these steps:
- Iterate through both the old and new lists of children simultaneously. If an old fiber can be reused for the new child at the same index, it is updated.
- If a mismatch is found (e.g., different key or type), the linear scan stops.
- The remaining old children are placed into a
Mapindexed by their key. - React continues iterating through the remaining new children. For each one, it attempts to find a match in the map.
- If a match is found, the old fiber is reused (a move).
- If no match is found, a new fiber is created (an insertion).
- Any fibers left in the map after the new children have been processed are marked for deletion.
This flowchart outlines the child reconciliation algorithm.
Sources: packages/react-reconciler/src/ReactChildFiber.js:1088-1323
Commit Phase
The Commit Phase is synchronous and cannot be interrupted. In this phase, React takes the effect list generated during the render phase and applies the actual changes to the host environment.
The HostConfig methods are heavily used here. The reconciler iterates through the effect list and performs the corresponding operations:
- Placement: A new node is inserted into the host tree using
appendChildorinsertBefore. - Update: An existing node's properties are updated using
commitUpdateorcommitTextUpdate. - Deletion: A node is removed from the host tree using
removeChild.
This sequence diagram shows the interaction between the reconciler and the host config during the commit phase.
Creating a Custom Renderer
To create a custom renderer, you must provide a HostConfig object to the react-reconciler factory function. This config object implements the methods necessary for React to manage the host tree.
Key HostConfig Methods
| Method | Description | Phase |
|---|---|---|
createInstance | Creates a new host instance (e.g., a DOM node). | Render |
createTextInstance | Creates a new host text instance. | Render |
appendInitialChild | Appends a child to a parent during the initial render. | Render |
finalizeInitialChildren | Called after all initial children are appended. Can be used for final mutations or to schedule a commitMount. | Render |
shouldSetTextContent | Optimization to set text content directly on a parent instead of creating a text node. | Render |
appendChild | Appends a child to a parent for updates. (Mutation Mode) | Commit |
insertBefore | Inserts a child before another in a parent. (Mutation Mode) | Commit |
commitUpdate | Called when an instance has updated props. (Mutation Mode) | Commit |
removeChild | Removes a child from a parent. (Mutation Mode) | Commit |
scheduleTimeout | Proxies to setTimeout. | - |
cancelTimeout | Proxies to clearTimeout. | - |
Sources: packages/react-reconciler/README.md
Conclusion
The Fiber Reconciler is the heart of React's rendering logic. Its architecture separates the reconciliation algorithm from the target platform, enabling React to be used in diverse environments beyond the web. By breaking work into smaller, manageable units (Fibers) and splitting the process into distinct render and commit phases, it provides the foundation for advanced features like concurrency, which are critical for building modern, responsive user interfaces. Understanding the Fiber reconciler and its HostConfig interface is key for anyone looking to extend React to new platforms or to gain a deeper insight into its internal workings.
Sources: packages/react-reconciler/README.md, packages/react-dom/src/tests/ReactDOMFiber-test.js