React Virtual DOM: Diffing, Keys and When It Adds Overhead

In short: the DOM (Document Object Model) is the tree of elements the browser actually shows. The React virtual DOM (VDOM) is a tree of plain JavaScript objects that describes what that user interface (UI) should look like. When state changes, React builds a new tree, compares it with the previous one (diffing), and writes only the differences to the actual DOM (commit).

Keys tell React which list items are the same between renders. The virtual DOM isn’t a speed trick that beats hand-written DOM code. It’s a way to keep UI updates correct and reasonably fast without you tracking every change by hand.

Most explanations stop at “React compares two trees and updates what changed”. That’s true, but it skips the parts that decide whether your app feels quick:

  • what triggers a render;
  • which rules the diffing algorithm follows;
  • why a bad key can wipe a user’s input;
  • when the extra layer costs more than it saves.

This guide walks through each step, from a state update to the browser repaint, and ends with a checklist you can reuse on any React project.

Why touching the real DOM is expensive

The DOM is the browser’s live, tree-like structure of nodes built from the HTML of a web page, often called the DOM tree. Each heading, paragraph and button is an HTML element in that tree, and JavaScript can read or change any of them. dhiwise.com walks through the specifics.

That reading and writing is what developers call DOM manipulation. Changing a node isn’t slow in itself, because a DOM node is an object like any other. The cost comes from what the browser must do next to show the change on screen.

After a DOM change, the browser may have to run some or all of this rendering work:

  • Style recalculation: work out which CSS rules apply to the changed elements.
  • Layout (reflow): compute the size and position of every affected box.
  • Paint (repaint): fill in the pixels for text, colours, borders and images.
  • Compositing: assemble the painted layers into the final frame.

One change is cheap. Frequent, scattered changes are costly, especially when code alternates between writing to the DOM and reading layout values such as offsetHeight. Each read after a write forces the browser to recompute layout immediately, a problem known as layout thrashing. At 60 frames per second the browser has about 16.7 ms per frame for everything, so wasted layout work quickly shows up as stutter.

Before React and similar libraries, direct DOM manipulation was the norm in every web application. Developers tracked which elements needed updating and grouped writes together, hoping they missed nothing. The virtual DOM moves that bookkeeping into the JavaScript library, as an abstraction between your code and the browser.

code on screen

What the React virtual DOM actually is

The virtual DOM is a lightweight, in-memory representation of the UI. In React, it consists of React elements: plain JavaScript objects with a type (such as 'div' or your Counter component), props and children. JSX, the HTML-like syntax used in React components, is just a friendlier way to create these objects.

// JSX
<button className="primary">Save</button>

// Roughly the object React works with
{ type: 'button', props: { className: 'primary', children: 'Save' } }

People often describe the virtual DOM as a lightweight copy of the real DOM, and that’s only half right. It holds no layout, no computed styles and no event machinery, which is why it’s cheap to create.

React also doesn’t keep a single giant object that it patches. Each render returns new element objects, and React keeps its own internal tree (the fiber tree, covered below) to remember what’s currently on screen.

The idea isn’t unique to React. Vue also renders through a virtual DOM, while Svelte and Solid skip it and update the DOM directly from compiled or reactive code. That contrast matters for the performance question later in this guide.

From state update to browser repaint, step by step

The React documentation describes every screen update in three steps: trigger, render and commit. The browser then paints. Here’s that flow with a simple counter.

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
  1. Trigger. A render starts on the initial mount or when state changes. Clicking the button calls setCount, which queues an update. React doesn’t touch the DOM at this point.
  2. Render. Because the component’s state changed, React calls Counter again. The function returns a new virtual DOM tree in which the heading text is now “Count: 1”. A change in state or props is what starts this re-rendering. If Counter had child components, React would call them too, unless memoization lets it skip them.
  3. Reconcile (diff). React compares the new tree with the previous one, a process called reconciliation. Here, the div, h2 and button keep the same type and position. Only one text value differs.
  4. Commit. React updates the real DOM with the minimal set of operations it found, in this case a single text update. It then runs layout effects and attaches refs.
  5. Paint. The browser recalculates styles and layout for the changed node, then repaints. React has finished its work before this step starts.

On the very first render there’s nothing to compare, so React creates every DOM node and appends it to the page. Diffing only happens on later renders.

React also groups state changes into a single batch update. If one event handler in a React component calls three state setters, React runs a single render and a single commit, not three, which avoids unnecessary work. Since React 18, this automatic batching also applies inside promises, setTimeout callbacks and native event handlers, not only React’s own event handlers.

code on screen

How the diffing algorithm finds the minimal changes

Comparing two arbitrary trees and finding the smallest edit between them is expensive. The best general algorithms run in the order of O(n³) operations for n elements, which would be far too slow for a UI with thousands of nodes. React’s documentation explains that it uses a heuristic O(n) algorithm instead, based on two assumptions:

  • two elements of different types produce different trees;
  • the developer can mark which children stay stable across renders with a key prop.

In practice, reconciliation follows three rules.

Rule 1: a different type replaces the whole subtree

If a <div> becomes a <section>, or <Article> becomes <Comment>, React doesn’t try to compare their contents. It unmounts the old node and everything below it, destroys their state, and builds the new subtree from scratch. This is fast to decide, but it can be expensive to execute on a large subtree.

Rule 2: the same type keeps the node and updates its props

If the type and position are the same, React keeps the existing DOM node and changes only the attributes that differ, such as a className or a style value. For a UI component of the same type, React preserves the instance and its state, then renders it with the new props.

Rule 3: children are compared in order, unless they have keys

For a list of children, React walks both lists at the same time. Without keys, it matches children by position. Virtual DOM in React Explained is a useful companion to this.

Appending an item at the end is cheap, because every existing child still matches. Inserting an item at the top is not: every child now sits in a different position, so React updates all of them. Keys solve this, as the next section shows.

Why keys matter in lists

A key is a stable identity for a list item. When React sees the same key in the old and new lists, it knows it’s the same item, even if it moved. It can then reorder the DOM node instead of rewriting it, and the component keeps its state.

React’s documentation sets two rules: keys must be unique among siblings, and they must not change between renders. A component never receives key as a prop.

// Good: identity comes from the data
{todos.map(todo => <TodoItem key={todo.id} todo={todo} />)}

// Risky: identity comes from the position
{todos.map((todo, index) => <TodoItem key={index} todo={todo} />)}

The index-as-key problem is easy to reproduce. Picture a list where each row has a text input. You type in the second row, then delete the first row.

With index keys, the row that was second now has key 0, so React reuses the first row’s component for it. The visible text from the data updates, but the uncontrolled input keeps the text you typed, now next to the wrong item. With todo.id as the key, React removes the right row and the typed text stays where it belongs.

Your list Use as key Avoid
Records from an API or database The record ID The array index
Items created in the browser An ID generated once, when the item is created (crypto.randomUUID()) An ID generated during render
Static list that never reorders or filters The index is acceptable Adding state to rows without revisiting the key
Groups of several elements per item <Fragment key={item.id}> The short <> syntax, which can’t take a key

Keys also work outside lists. Changing a component’s key on purpose forces React to treat it as a new component and reset its state, for example <ProfileForm key={userId} /> when the user switches profiles.

code on screen

Is the virtual DOM faster? The myth, with small benchmarks

“React is fast because of the virtual DOM” is the most repeated claim about it, and it’s only half true. Dan Abramov, a member of the React team, answered “no” when asked whether React is faster than the DOM. The virtual DOM is extra work on top of the DOM. It can only win against DOM code that does more than necessary, such as inefficient re-rendering of whole sections.

Take the counter above.

A hand-written version updates the heading with one line: heading.textContent = 'Count: ' + count. React ends with that same single DOM write. Before it, though, it calls the component, allocates new element objects, and diffs them against the old ones. For one known change, direct DOM code always does less work.

You can check this yourself with a small benchmark. It’s an example to run on your own machine, since results vary by device and browser:

// Example benchmark: update one cell in a 1,000-row table
const t0 = performance.now();
cell.textContent = 'updated';          // direct DOM
const t1 = performance.now();
console.log('direct:', t1 - t0, 'ms');
// Then trigger the same change through setState in a React version
// and read its duration in the React DevTools Profiler.

The direct version wins this kind of test, so the idea that the virtual DOM is faster than the DOM doesn’t hold on its own. The virtual DOM adds overhead in three typical situations:

  • Small, targeted updates, such as a clock or a live price, where you already know the one node to change.
  • Large trees and a tiny change: a state change high in the tree makes React call and diff every child without memoization. The DOM may barely change.
  • Memory: React keeps a description of the previous UI in memory to compare against.

Where it does help is the realistic case: many changes from many sources in a React application, written by a team.

Naive code that rebuilds a whole section with innerHTML on every change will lose to React, because React turns those rebuilds into a few targeted writes. The real gain is correctness. You describe the UI for a given state, which is declarative code, and React works out the DOM operations. In our view, that’s the right reason to choose React for a client project, not raw speed.

Virtual DOM vs other approaches

Not every framework needs a virtual DOM. A compiler or a fine-grained reactivity system can know at build time, or through tracked signals, exactly which node depends on which value. It then updates that node directly, with no tree to compare.

Approach Examples Cost per update Best fit
Hand-written DOM updates Vanilla JavaScript Lowest, if done well Small widgets, mostly static pages
Virtual DOM diffing React, Vue Render and diff, then minimal writes Large apps, big teams, rich ecosystem needs
Compiled or fine-grained updates Svelte, Solid Direct writes to known nodes Performance-sensitive UIs, smaller bundles

The virtual DOM is also easy to confuse with the Shadow DOM, and they have nothing in common. The Shadow DOM is a browser standard, part of Web Components, that hides a component’s internal markup and CSS from the rest of the page. The virtual DOM is a library technique that lives in JavaScript memory. The real DOM is the one the browser actually displays. There is more on it in How React’s Virtual DOM Works.

code on screen

React Fiber, concurrent rendering and the React Compiler

React Fiber is the reconciliation engine React has used since version 16, released in 2017. It rewrote the older “stack” reconciler, which processed a whole tree in one uninterrupted pass. Fiber splits rendering into small units of work, one fiber per element, so React can pause, resume, prioritise or discard work when a more urgent update arrives.

That split only applies to the render phase. The commit phase still runs in one go, so users never see a half-updated screen. Fiber is what makes concurrent features possible, such as startTransition, which marks an update as non-urgent so typing in an input stays responsive while a heavy list re-renders.

The React Compiler, released as version 1.0 in October 2025, attacks the main overhead described above. It applies a common performance optimization, memoization, automatically at build time, so components skip rendering when their inputs haven’t changed. Before it, developers did this by hand with React.memo, useMemo and useCallback. The virtual DOM and diffing still exist; the compiler just gives React less to compare.

Common pitfalls, and how to fix them

Typed text jumps to another row. The cause is index keys on a list that you reorder, filter or remove items from. Use a stable ID from the data as the key.

An input loses focus after each keystroke. The usual cause is a component defined inside another component. Each render creates a new function, so React sees a new type and remounts it (rule 1). Declare components at the top level of the module.

The whole list re-renders and remounts constantly. The cause is a key generated during render, such as Math.random(). Every render produces new keys, so React destroys and recreates every item. Generate IDs once, when you create the data.

Typing feels laggy in a big form or dashboard. The cause is often state that lives too high in the tree, so each keystroke re-renders and diffs everything below. Move the state down to the component that uses it, memoize heavy children, or wrap the slow update in startTransition.

The profiler shows every component rendering twice. This is StrictMode in development, which deliberately calls components twice to expose impure code. Always measure performance on a production build.

code on screen

How to measure what the virtual DOM is doing

Guessing about re-renders is a waste of time, because the tools show them directly. For a typical client project, these three checks cover most needs:

  1. React DevTools Profiler. Record an interaction, then read which components rendered, why, and for how long. The “Highlight updates when components render” setting flashes every component that renders, which quickly reveals wasted work.
  2. Chrome DevTools Performance panel. Record the same interaction and look at the split between scripting (React’s render and diff) and rendering (layout and paint). Long purple layout blocks point to DOM cost; long yellow scripting blocks point to rendering too much.
  3. Interaction to Next Paint (INP). This Core Web Vital measures how long the page takes to respond visually to a click, tap or key press, so it reflects the user experience directly. Google’s web.dev rates an INP of 200 ms or less as good. Check it in your field data or in PageSpeed Insights.

For a small brochure site with little interaction, these numbers rarely move. For dashboards, filters and long forms, measure before and after each optimization rather than adding memo everywhere by reflex.

React virtual DOM checklist

  1. Give every list item a stable, unique key from the data.
  2. Never generate keys during render.
  3. Declare components at the top level, never inside another component.
  4. Keep state as close as possible to the components that use it.
  5. Keep element types stable where state must survive (rule 1).
  6. Use a key change on purpose when you want to reset a component.
  7. Avoid reading layout values right after writing to the DOM in effects.
  8. Use startTransition for heavy, non-urgent updates.
  9. Profile with React DevTools on a production build before optimizing.
  10. Track INP on real pages after each release.

Conclusion

The React virtual DOM is a bookkeeping system, not a turbocharger: render a description, diff it with clear rules, commit the minimum. Once you see it that way, the next step is concrete. Open the React DevTools Profiler on the slowest screen of your current project, record one interaction, and check the keys and state placement of whatever lights up.

For more practical guides on building fast, maintainable websites and web apps, browse the other articles on our blog.

FAQ

What is <> and </> in React?

It’s the short syntax for a Fragment. It lets a component return several elements without wrapping them in an extra div, so no extra node appears in the DOM. If you need a key, for example in a list, use the full <Fragment key={id}> form instead.

Is Vue easier than React?

Many developers find Vue’s templates easier to start with, but “easier” depends on your background and team. Under the hood both render through a virtual DOM, and Vue’s compiler adds hints that help it skip static parts of a template. For a client project, the team’s existing skills usually matter more than the framework.

Does React Native use the virtual DOM?

React Native uses the same React reconciliation, but there’s no browser DOM to update. Instead of DOM nodes, the commit step creates and updates native iOS and Android views. That’s one reason React keeps its core separate from the renderer, such as react-dom.

Can I access or edit the virtual DOM directly?

No, React has no public API for it, and you shouldn’t need one. When you must touch a real DOM node, for focus, measurements or a third-party widget, use a ref. Changing nodes that React manages behind its back can make the next diff produce wrong results.

Does the virtual DOM affect SEO?

Not directly. What matters for search engines is the HTML they receive and can render. Server-side rendering or static generation, as offered by frameworks like Next.js, sends ready-made HTML, and React then attaches to it in the browser through a step called hydration.