Chapter 2 of 4

How React Updates the Screen

Elements, the virtual DOM, and what actually happens when state changes.

To use React well it helps to know roughly what happens between your code and the pixels on screen. You do not need the internals, just the shape of the process.

Elements are plain objects

When you write JSX, you are not creating DOM nodes. You are creating small plain JavaScript objects that describe what you want. These are called React elements.

A React element is a cheap description, not a DOM node.
// This JSX...
const heading = <h1 className="title">Hello</h1>;

// ...becomes roughly this object
{
  type: "h1",
  props: { className: "title", children: "Hello" }
}

Because elements are just objects, creating them is fast and throwing them away costs almost nothing. That is what makes the next step affordable.

Rendering and reconciliation

A render is React calling your components to get a fresh tree of elements. React then compares that new tree with the previous one and works out the smallest set of real DOM changes needed. That comparison step is called reconciliation, and the in-memory tree is often called the virtual DOM.

  1. Something changes: a user event, a state update, or new props from a parent.
  2. React calls the affected components again, producing a new element tree.
  3. React diffs the new tree against the previous one.
  4. React applies only the differences to the real DOM. This is the commit.

Why the whole component re-runs

A common surprise for newcomers is that when state changes, React calls your entire component function again from the top. Every line runs, every variable is recreated. Only the DOM updates are minimal, not the function calls.

function Greeting({ name }) {
  console.log("rendering"); // runs on every render
  const greeting = "Hello, " + name;
  return <p>{greeting}</p>;
}
Outputrendering

This is why React components should be predictable: given the same props and state, they should produce the same output, and they should not change things outside themselves while rendering.