Why Not Just Re-Render the Whole Real DOM
Exploring why not just re-render the whole real dom and common implementation patterns
1. The Problem
State changed. You know what the UI should look like now. The fastest path to a correct screen is to throw away what is there and rebuild it from scratch. One operation. No diffing. No tracking. No incremental updates. Just wipe and re-render.
This is not a naive idea. It is the default behavior of almost every template-based rendering system ever written. Server-rendered HTML works this way: the server produces a complete document from scratch on every request. Early jQuery applications worked this way: $('#container').html(renderTemplate(data)). It is simple, predictable, and correct by construction. If the output is derived purely from the current state, wiping and re-rendering is always right.
The question is whether you can afford it in a client-side application running at 60 frames per second, where “re-render” means issuing real DOM operations against a live browser document, not producing a string on a server.
2. The Naive Attempt
Build a filterable list. A text input. A list of 500 items. As the user types, the list filters to matching items.
First instinct: on every keystroke, wipe the list and rebuild it.
const items = Array.from({ length: 500 }, (_, i) => `Item ${i + 1}`);
const container = document.getElementById('list');
const input = document.getElementById('filter');
function render(filter) {
const filtered = items.filter((item) => item.toLowerCase().includes(filter.toLowerCase()));
container.innerHTML = filtered.map((item) => `<li>${item}</li>`).join('');
}
input.addEventListener('input', (e) => render(e.target.value));
render('');
On every keystroke, innerHTML is set. The browser parses the HTML string, destroys every existing <li> node, creates new ones, inserts them, recalculates layout, repaints. For 500 items this may be acceptable. For 5,000 items with complex list item markup - nested elements, images, event listeners - it will visibly lag. The input feels sticky. Animations stutter. Scroll position resets.
The problem compounds when list items have state. Focused elements lose focus. Input cursors jump. CSS transitions abort. The browser had context attached to those nodes. Wiping the DOM discards all of it.
Now make each list item interactive. A checkbox. A nested expand/collapse. A tooltip on hover. Wiping and re-rendering innerHTML destroys all event listeners attached to those nodes. You must re-attach them after every render. And any user interaction mid-render - keyboard focus, a tooltip open - is silently destroyed.
function render(filter) {
const filtered = items.filter((item) => item.toLowerCase().includes(filter.toLowerCase()));
// all event listeners attached to old nodes are gone
// any focused element loses focus
// any open tooltip is closed
// scroll position may shift
container.innerHTML = filtered
.map(
(item) => `
<li>
<input type="checkbox" data-id="${item}" />
<span>${item}</span>
</li>
`,
)
.join('');
// must re-attach all listeners
container.querySelectorAll('input[type=checkbox]').forEach((cb) => {
cb.addEventListener('change', handleCheckboxChange);
});
}
Every render cycle: full DOM destruction, full DOM construction, full listener re-attachment. The cost scales with the size of the subtree, not with the size of the change.
3. Why That Breaks
The precise failure mode: DOM operations are not proportional to the logical size of the change. They are proportional to the size of the subtree being rebuilt, and they trigger browser work - style recalculation, layout, paint - that dwarfs the cost of the JavaScript that drives them.
There are two distinct cost categories here, and conflating them causes bad intuitions about performance.
JavaScript cost. Producing a new description of the UI - calling component functions, building object trees, diffing - happens entirely in the JS engine. The JS engine is fast. It operates on heap-allocated objects with no layout engine involvement. A full Virtual DOM tree construction and diff for a 500-node component tree takes microseconds on modern hardware.
DOM cost. Touching the DOM crosses the boundary between the JavaScript engine and the browser’s rendering engine. They are separate subsystems. Every DOM mutation - appendChild, removeChild, setAttribute, textContent = ... - is a cross-subsystem call. And more importantly, the rendering engine does not apply DOM mutations individually. It batches them and then runs a cascade:
- Style recalculation. Which CSS rules apply to each node now?
- Layout (reflow). What are the position and dimensions of each node? This is recursive: a node’s size depends on its children’s sizes, which depend on their children.
- Paint. Rasterize the visual output of each node.
- Composite. Combine painted layers into the final frame.
Reflow is the expensive step. It is O(n) to O(n²) depending on what changed and what layout properties are involved. Changing the width of a parent may require recalculating the layout of every descendant. Inserting or removing nodes from the middle of a document flow recalculates layout for all subsequent siblings. Wiping and rebuilding a 500-node subtree triggers a full reflow of that subtree, plus any ancestors whose layout depends on it.
This is why “DOM ops are expensive, JS is fast” is the mental model. It is not that DOM objects are inherently slow to create. It is that creating them in a live document triggers rendering engine work that dwarfs the creation cost itself.
4. React’s Mental Model
Never touch the DOM unless you know exactly which node needs to change and what specifically needs to change about it.
To know what specifically needs to change, you need a record of what the DOM currently looks like and a description of what it should look like. Diffing those two descriptions in JavaScript - fast, no rendering engine involvement - tells you the minimal set of mutations to apply. You then apply exactly those mutations and nothing else.
One sentence: keep two JS descriptions of the UI, diff them cheaply in JS, apply only the diff to the expensive DOM.
The Virtual DOM is the mechanism for holding those two descriptions. Reconciliation is the diff. The commit phase is the minimal mutation pass.
5. React’s Solution
React’s rendering pipeline separates into three phases precisely to minimize DOM contact:
Render phase. React calls your component functions and builds a new Virtual DOM tree - a tree of plain JS objects. No DOM is touched. This can be interrupted, restarted, or thrown away. It is pure computation.
Reconciliation. React compares the new Virtual DOM tree against the previous one. For each node, it determines: same type, same position? Update props in place. Different type? Schedule deletion and insertion. New node? Schedule insertion. Removed node? Schedule deletion. The result is a list of effects - specific mutations to make. Still no DOM contact.
Commit phase. React walks the effect list and applies each mutation to the real DOM. setAttribute, textContent, appendChild, removeChild - the minimum set required to bring the DOM into sync with the new description. One pass. Synchronous. DOM contact happens only here.
The practical consequence:
// React's version of the filterable list
function FilterableList({ items }) {
const [filter, setFilter] = React.useState('');
const filtered = items.filter((item) => item.toLowerCase().includes(filter.toLowerCase()));
return (
<div>
<input value={filter} onChange={(e) => setFilter(e.target.value)} />
<ul>
{filtered.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}
When the filter changes, React does not wipe <ul> and rebuild it. It diffs the old list of <li> elements against the new list. Items that remain in the list keep their existing DOM nodes, which retain focus state, CSS transition state, and any browser context attached to them. Only removed items are deleted from the DOM. Only new items are inserted. Existing items that need text updates get a targeted textContent mutation and nothing else.
The DOM operations are proportional to the size of the change, not the size of the list.
6. Internals
The browser rendering pipeline makes the cost of unnecessary DOM mutations concrete. Understanding it explains why minimizing DOM contact is not a micro-optimization but the central performance constraint of client-side UI.
The rendering pipeline in detail.
When a DOM mutation occurs, the browser does not immediately repaint. It invalidates the affected nodes and schedules a rendering update. Before the next frame, it runs:
Style recalculation. The CSS cascade is recomputed for every invalidated node. Selector matching, specificity resolution, inherited property propagation. Cost scales with the number of invalidated nodes and the complexity of the stylesheet.
Layout (reflow). The browser computes the box model for every invalidated node: position, dimensions, margins, padding. Layout is recursive. A node’s size depends on its children. If a parent’s width changes, every child that uses percentage widths must be recalculated, and their children after them. Reflow is one of the most expensive operations in the browser. It blocks the main thread. If it takes longer than 16ms, the frame is dropped.
Paint. The browser rasterizes the visual output of each node into layers. Text rendering, border drawing, background colors, images. GPU-accelerated properties (transform, opacity) skip this step and go directly to composite.
Composite. Painted layers are combined into the final frame and sent to the display.
Wiping and rebuilding a 500-node subtree invalidates all 500 nodes. Style recalculation runs for all 500. Layout runs for all 500, plus any ancestors whose size depends on descendants. Paint runs for all visible nodes. On a mid-range device, this is measurable frame time. Do it 10 times per second (normal keystroke rate for a fast typist), and you have a budget problem.
Forced synchronous layout.
The most dangerous DOM performance pattern is forced synchronous layout: reading a layout property immediately after writing to the DOM.
// SLOW: forced synchronous layout
elements.forEach((el) => {
const width = el.offsetWidth; // READ: forces layout to flush
el.style.width = width + 10 + 'px'; // WRITE: invalidates layout
});
// each iteration forces a full layout recalculation
When you write to the DOM, the browser marks layout as dirty. When you read a layout property (offsetWidth, getBoundingClientRect, scrollTop), the browser must flush the dirty layout to give you an accurate answer. Alternating reads and writes in a loop forces a layout recalculation on every iteration. This is called layout thrashing, and it is the fastest way to make a DOM-heavy application drop frames.
React’s commit phase avoids this entirely. It does all DOM writes in a single pass, never reading layout properties during the commit. The browser sees one batch of mutations and runs one layout/paint cycle.
Why innerHTML is particularly expensive.
Setting innerHTML does more than create nodes. The browser must:
- Parse the HTML string into a new DOM tree (HTML parsing is not free).
- Destroy every existing child node and its associated browser context (layout boxes, style data, event listener registrations, accessibility tree entries).
- Insert the new nodes into the document and attach them to the render tree.
- Run style recalculation, layout, and paint for the entire affected subtree.
Additionally, nodes destroyed by innerHTML are not just removed from the DOM. Their C++ objects in the browser’s rendering engine are dereferenced. Any JavaScript references to those nodes become detached node references - they still exist in JS heap until GC, but they point to nodes that are no longer in the document. If you had event listeners attached to them via addEventListener, those listeners are now attached to orphaned nodes. They will never fire.
React avoids innerHTML entirely. Every DOM mutation is a targeted operation on a specific node’s specific property. The browser’s rendering engine updates only what changed. The rest of the DOM is undisturbed.
7. Interview Traps
Trap 1: “React’s Virtual DOM makes DOM operations faster.” Correct this statement precisely.
Answer
React’s Virtual DOM does not make individual DOM operations faster. A setAttribute call issued by React costs exactly the same as one issued by vanilla JS. The browser does not know or care who called it.
What React’s Virtual DOM does is reduce the number of DOM operations issued. By diffing two JS object trees before touching the DOM, React determines the minimal set of mutations required to bring the DOM from its current state to the desired state. A re-render that produces no visible change issues zero DOM mutations. A re-render that changes one text node issues one textContent assignment. A re-render that changes one attribute on one element issues one setAttribute.
Without diffing, a declarative rendering approach would rebuild the entire DOM subtree on every state change, issuing O(n) mutations where n is the subtree size. With diffing, it issues O(d) mutations where d is the number of differences. For most interactive state changes, d is much smaller than n.
The correct statement: React’s Virtual DOM reduces the number of DOM operations, which reduces the amount of rendering engine work (style recalculation, layout, paint) the browser performs per state change.
Trap 2: If JS is fast and DOM is slow, why not avoid the DOM entirely and render to a canvas?
Answer
You can, and some high-performance applications do. React Native on web and game engines use canvas rendering. The tradeoff is real.
DOM rendering is slow but gives you the browser’s entire accessibility tree, tab focus management, native form controls, text selection, scroll behavior, CSS animations, media queries, and screen reader support for free. These are not trivial. They represent years of platform work and are expected behavior for users, especially users who rely on assistive technology.
Canvas rendering is fast because it bypasses all layout and compositing overhead - you control every pixel. But you lose everything above. You must implement your own text layout, hit testing, focus management, and accessibility. You are writing a UI toolkit from scratch, not using one.
React’s answer is to minimize DOM operations, not eliminate them. The diffing approach brings DOM rendering close enough to canvas performance for most applications while retaining the full browser platform. For specific cases - data grids with tens of thousands of rows, real-time data visualizations - the answer is virtual scrolling, canvas layers, or OffscreenCanvas, applied surgically to the bottleneck, not globally.
Trap 3: A developer sets innerHTML on a container to update a list, claiming it is faster than React because it is one operation instead of many. Under what conditions are they right, and under what conditions are they wrong?
Answer
They are right in a narrow case: if the list is small, changes infrequently, contains no interactive elements, and no browser context (focus, transitions, selections) needs to be preserved. In that case, innerHTML is genuinely simpler and the performance difference is immeasurable.
They are wrong in most real conditions. First, innerHTML is not one operation to the browser. It is HTML parsing, full subtree destruction, full subtree insertion, style recalculation, layout, and paint - an O(n) cascade where n is the subtree size, regardless of how much changed. A React diff for a one-item change in a 500-item list is O(500) for the comparison and O(1) for the DOM mutation. The innerHTML approach is O(500) for both.
Second, innerHTML destroys browser context. Any focused element loses focus. Any open tooltip or dropdown closes. CSS transitions in progress abort. Custom element lifecycle methods for removed nodes may fire unexpectedly. JavaScript references to old child nodes become detached. If the list items are interactive - checkboxes, inputs, expandable rows - these are not theoretical concerns. They are observable bugs.
Third, innerHTML requires event delegation or listener re-attachment after every render, because the old nodes with their listeners are gone. React retains DOM nodes for unchanged items and their attached listeners across renders.
The developer’s claim treats performance as a single axis. It is not. innerHTML wins on code simplicity for simple static content. React wins on correctness and performance for interactive, frequently-updating subtrees.
Self-Test
Q1. Name the four stages of the browser rendering pipeline that a DOM mutation triggers. Which stage is typically the most expensive and why?
Answer
Style recalculation, layout (reflow), paint, composite.
Layout is typically the most expensive. It is recursive: a node’s dimensions depend on its children, which depend on their children. Changing the width or height of a parent can force recalculation of every descendant’s layout. Inserting or removing a node from document flow forces layout recalculation for all subsequent siblings. For large subtrees with complex layout - flexbox, grid, absolutely positioned children - this can take milliseconds per reflow. Because it blocks the main thread, any reflow that exceeds the frame budget (16ms at 60fps) drops a frame. Style recalculation is also significant for large stylesheets, but layout is the more common bottleneck for DOM-heavy applications.
Q2. What is layout thrashing? Write a code example that causes it, and a corrected version that avoids it.
Answer
Layout thrashing occurs when JavaScript alternates between reading layout properties and writing to the DOM in a loop, forcing the browser to run a full layout recalculation on every iteration rather than batching mutations and running one layout pass at the end.
Causing it:
// forces layout recalculation on every iteration
boxes.forEach((box) => {
const w = box.offsetWidth; // READ: flushes dirty layout
box.style.width = w * 2 + 'px'; // WRITE: invalidates layout
});Each offsetWidth read forces the browser to resolve the pending dirty layout from the previous iteration’s write. One layout recalculation per box.
Corrected:
// batch all reads first
const widths = boxes.map((box) => box.offsetWidth); // all READs
// then all writes
boxes.forEach((box, i) => {
box.style.width = widths[i] * 2 + 'px'; // all WRITEs
});
// one layout recalculation total, deferred to next frameAll reads happen before any writes. The browser runs exactly one layout pass. This pattern - read batch, write batch - is the fundamental rule for avoiding layout thrashing in any DOM-heavy code.
Q3. React separates its work into render, reconciliation, and commit phases. Which phases touch the real DOM, and why does separating them matter?
Answer
Only the commit phase touches the real DOM. The render phase calls component functions and produces Virtual DOM element trees - pure JavaScript computation, no browser involvement. The reconciliation phase diffs old and new Virtual DOM trees and produces an effect list - still pure JavaScript. The commit phase applies the effect list to the real DOM as a single synchronous mutation pass.
Separating them matters for two reasons. First, it allows React to batch all DOM mutations into a single pass, avoiding the interleaved read-write patterns that cause layout thrashing. The commit phase only writes; it never reads layout properties mid-commit. The browser sees one batch of mutations and runs one style/layout/paint cycle.
Second, it makes the render and reconciliation phases interruptible. Because they are pure JavaScript computation with no DOM side effects, React can pause them mid-tree, handle a higher-priority update, then resume or restart. If the work were applied directly to the DOM as it was computed, interrupting a partial render would leave the DOM in an inconsistent intermediate state. The separation of description from application is what makes Concurrent Mode possible.
Q4. A 1,000-row table re-renders. Only one cell’s value changed. How many DOM mutations does React issue, and how does it know which ones to skip?
Answer
React issues one DOM mutation: the textContent (or equivalent attribute) update on the single cell that changed.
It knows which rows to skip through reconciliation. React compares the new Virtual DOM tree for the table against the previous one. For each row, it checks whether the type (tr) is the same and whether the props are referentially equal or shallowly equal. For 999 rows whose data did not change, the props object is identical - same column values, same key - so React marks those Fiber nodes as having no update work. It traverses past them without producing any effect entries.
For the one row that changed, React finds the differing prop, traverses into its children to find the changed cell, and marks that cell’s Fiber with an Update effect. The commit phase walks the effect list, finds one entry, and issues one textContent mutation.
This is why key stability matters. If row keys change between renders - for example, using array index as key when rows are reordered - React cannot correlate old and new rows. It may destroy and recreate rows that could have been updated in place, converting one mutation into thousands.