React’s Render Phase and the Reconciler
1. What is "render"?
When we talk about "render" in React, we mean two related things:
a. The Render Phase (Virtual DOM Generation) - React invokes your component functions (or render() methods) to produce a tree of React elements—often called the “virtual DOM.”
Characteristics:
-
Pure: Given the same props and state, your component always returns the same element tree.
-
Side‑effect free: You shouldn’t read or write to the real DOM, perform data fetching, or trigger animations here. Those belong in lifecycle methods or hooks like useEffect.
-
Interruptible: React can pause, resume, or even abandon this work if a higher‑priority update arrives (e.g. a user‑initiated event).
1function UserCard({ user }: { user: User }) { 2 // ➜ Render phase: returns React elements, no side‑effects 3 return ( 4 <div className="user-card"> 5 <h2>{user.name}</h2> 6 <p>{user.email}</p> 7 </div> 8 ); 9} 10
b. Entry‑Point Rendering (Mounting)
-
ReactDOM.render / root.render: The public API you call once at app startup. It tells React, “Here’s your top‑level component—mount it into the real DOM container.”
-
In React 18: You use the new createRoot API, which spins up the concurrent reconciler under the hood.
1import { createRoot } from 'react-dom/client'; 2 3const container = document.getElementById('root')!; 4const root = createRoot(container); 5root.render(<App />); 6
2. The Reconciler
Once React has a fresh element tree from your render phase, it needs to diff it against the previous tree and apply only the minimal changes to the real DOM. That’s the job of the reconciler.
a. Fiber: React’s Internal Data Structure - Fiber nodes represent elements in your tree.
React maintains two trees:
-
Current tree: what’s currently on screen.
-
Work‑in‑progress tree: what React is building during the render phase.
Fibers are linked lists allowing React to pause and resume work at any node.
b. The Two‑Phase Update - Render (Reconciliation Preparation)
- Walk both old and new trees in parallel.
- For each Fiber, compare element types and props.
- Mark each Fiber with an effect tag, such as:
- PLACEMENT (insert a new node)
- UPDATE (change props/text)
- DELETION (remove from DOM)
- Commit (DOM Mutation)
- Apply all collected effects in a single, batched pass.
- Run synchronous lifecycle hooks (componentDidMount, useLayoutEffect) and, later, deferred hooks (useEffect).
c. Prioritization & Concurrency
React 18’s concurrent mode allows React to:
- Schedule low‑priority updates (e.g. data fetching) behind high‑priority ones (e.g. typing, clicks).
- Interrupt long render work if a more urgent update arrives, keeping the UI responsive.