Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 132 ยท Getting Started

How React Works

Understand how React turns components into a screen - declarative UI, elements vs components, the render and commit phases, reconciliation, keys and renderers.

You can use React for a long time without knowing what happens between "I called a state setter" and "the page changed". But the people who debug React quickly, and who write fast React, all carry the same small mental model in their heads. This lesson builds it from the ground up, with runnable experiments instead of diagrams you have to take on trust.

By the end you will know the difference between an element and a component, what the render phase and the commit phase each do, how reconciliation decides what to update, why keys exist, and how the same React core can draw to a browser page, a phone screen or a plain string.

Declarative versus imperative

There are two ways to tell a computer how to build a user interface.

An imperative program gives step-by-step orders: create a <ul>, create an <li>, set its text, append it, later find that item and remove it. You manage every change yourself.

A declarative program states the goal: "for these three items, the screen is a list with three entries". The system figures out the steps. HTML is declarative for the first screen. React makes the updates declarative too: you describe the screen for the current data every time, and React works out the steps to get from the old screen to the new one.

JSX
// Imperative (what you would do by hand)
//   list.appendChild(newItem); ... later ... list.removeChild(oldItem);

// Declarative (what you write in React)
<ul>
  {items.map((item) => (
    <li key={item.id}>{item.name}</li>
  ))}
</ul>

You never write the appendChild or removeChild calls. If items has one more entry on the next render, React adds an <li>. If it has one fewer, React removes one.

Elements are descriptions, components are recipes

Two words get mixed up constantly, so let us nail them down.

  • A React element is a small plain JavaScript object that describes a piece of UI: "an h1 with these props and these children". It is not a DOM node and it is cheap to create. JSX produces elements.
  • A component is a function that returns elements. React calls it whenever it needs to know what to show.

You can see this directly. Write JSX, store it in a variable and look at what it is:

Elements are plain objects

The first element has type: 'h1' (a string: a built-in tag) and the second has type: Greeting (the function itself). Neither has run any of your component code yet. <Greeting name="Ada" /> is just a note saying "when you get to this spot, call Greeting with { name: 'Ada' }". React does the calling during rendering.

That is why you never write Greeting({ name: 'Ada' }) yourself and why component names must be capitalized: the capital letter tells JSX to keep the function reference as the type, rather than turning the name into a string tag.

Two phases: render, then commit

Every update React performs has the same shape, and it is worth learning the vocabulary.

  1. Trigger. Something asks for a render: the first root.render(...), or a state setter being called.
  2. Render. React calls your components to find out what the UI should now look like. This phase is pure calculation: it produces a tree of elements and does not touch the page.
  3. Commit. React applies the differences to the real DOM, then runs refs, layout effects and finally effects.

The crucial consequence: "rendering" in React does not mean "drawing to the screen". It means "calling your component functions". A component can render without anything on the page changing at all, if the output is identical.

Here is a program that logs what happens in each phase. The component body runs in the render phase. The ref callback, useLayoutEffect and useEffect all belong to the commit phase.

Render phase versus commit phase

Look at the console after the first run and again after one click. The order of the numbers is the order of the lifecycle: first the function body (render), then the ref and the layout effect (the DOM exists and has the new text), and last the passive effect. The numbers stay in order on every update. (The ref callback is a new function on each render, so React calls the old one with null and then the new one with the button; the if (node) check skips the null call.)

Render is allowed to run more than once for a single update (React can pause, restart or repeat it, and in development StrictMode deliberately calls it twice to expose impure code). Commit runs once. That is why side effects such as network calls or subscriptions never belong in the body of a component; they go in event handlers or effects. Keeping Components Pure builds on this.

Reconciliation: how React decides what to change

After a render, React has two element trees: the previous one and the new one. Comparing them to find the minimal DOM changes is called reconciliation. A general tree diff is a very expensive problem, so React uses two simple rules that are right almost all the time:

  1. Different type at the same position means a different thing. If the old element was a <div> and the new one is a <span>, or a <Counter> became a <Profile>, React throws away the old subtree (including the state of everything inside it) and builds a new one.
  2. Same type at the same position means the same thing. React keeps the existing DOM node or component instance and only updates the changed props. The state inside the component is preserved.

The consequence you can feel: state belongs to a position in the tree, not to a component function. Try the demo. Type something in the box, then flip between the two modes.

Same position and type keeps state

Type in both inputs, then tick the checkbox. In the first block the typed text survives even though the label changed: it is still a NameBox in the same spot, so React updated its prop and kept its state. In the second block the text disappears: the div became a section, so React unmounted the old subtree and mounted a new NameBox with fresh state.

This is not a quirk; it is the design. It is also the tool behind resetting a form by changing its key, covered in useState and Reconciliation and Keys in Depth.

Why keys matter

Position works well for fixed layouts. For lists the order can change, items can be inserted at the top or removed from the middle, and "position 2" no longer means "the same item". A key is a stable identity you attach to each list item so React can match old and new items by identity instead of position.

In the demo, both lists hold the same three people, each with an input. Type something into each input in both lists, then press Reverse.

Keys keep identity when a list reorders

In the first list, the notes travel with the names, because each row is matched to its person. In the second, the names swap but the notes stay in the same place: with index keys, row 0 is always "the same row", and React just gave it a different name. Whatever lives inside that row (input text, focus, internal state) now belongs to the wrong person.

Rules of thumb that follow:

  • Give every list item a key that is unique among its siblings and stable over time (an id from your data).
  • Do not use the array index if the list can be reordered, filtered or inserted into. Index keys are only fine for static lists that never change.
  • Do not use Math.random() or a new value on every render. A key that changes on each render makes React remount the whole row every time.

React warns about missing keys in development. Rendering Lists and Keys goes through the details.

What runs where: React, React DOM and other renderers

React is split into two layers:

  • react knows about components, elements, state and hooks. It has no idea what a browser is.
  • A renderer knows how to turn the committed tree into something real. react-dom targets the browser DOM. React Native targets iOS and Android views. Others exist for terminals, PDFs and canvas.

That split is why import { useState } from 'react' looks the same in a website and in a mobile app, while import { createRoot } from 'react-dom/client' is browser-only. A neat way to feel the separation is to render to a string with the server flavour of react-dom: same components, no browser tree at all.

The same components rendered to a string

The console shows plain HTML text, produced by calling the components without ever creating a DOM node. Servers use this idea to send a ready-made page to the browser, which then hydrates it: React attaches event handlers to the existing HTML instead of building it from scratch. That is the basis of server-side rendering and frameworks such as Next.js (Setting Up a React Project).

Putting it together

When you click a button whose handler calls a state setter:

  1. React marks the component as needing an update (trigger).
  2. It calls your component function with the new state (render), and every child component whose input could have changed.
  3. It compares the new elements with the old ones, node by node, using type, position and key (reconciliation).
  4. It applies only the differences to the DOM, then runs ref callbacks and effects (commit).

Nothing in this process involves you finding elements or writing DOM instructions, and nothing in it requires the virtual tree to be "faster than the DOM". The benefit is mainly correctness and clarity; React's diffing keeps the cost reasonable. The performance chapter shows how to measure and reduce re-rendering when it does become a problem, starting with Rendering in Depth.

"Virtual DOM" is often described as a speed trick. A more useful way to think of it: it is the description that makes declarative programming possible. Speed comes from React doing a small, targeted DOM update instead of rebuilding everything, not from the virtual tree itself being free.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a React element?

    An element is a lightweight description (a type plus props), created by JSX. React uses elements to decide what to put in the DOM. It is not itself a DOM node.
  2. 2. Which of these belong to the commit phase?

    Render is calling components to calculate the new tree. Commit is applying the result to the DOM and running ref callbacks, layout effects and effects.
  3. 3. A <div> at some position in your tree becomes a <section> on the next render, and a stateful component sits inside. What happens to the component's state?

    When the element type at a position changes, React tears down the old subtree and mounts a new one, so state inside is lost.
  4. 4. Why is using the array index as a key a problem for a list that can be reordered?

    React matches rows by key. With index keys, row 0 is always row 0, so whatever state it holds stays at that position even when different data is shown there.
  5. 5. Which package knows how to draw React components in a web page?

    react holds components and hooks; a renderer such as react-dom turns the result into browser DOM. React Native does the same for mobile views.

Summary

  • React is declarative: you describe the UI for the current state and React works out the DOM changes.
  • Elements are cheap objects describing UI; components are functions that return elements and are called by React.
  • An update has a trigger, a render phase (pure calculation, calling components) and a commit phase (DOM changes, refs, effects).
  • Reconciliation compares old and new trees: a different type at a position resets the subtree, the same type keeps its state.
  • Keys give list items a stable identity; use ids from your data, not indexes, for lists that change.
  • react is renderer-agnostic; react-dom renders in browsers, React Native on phones, and react-dom/server can render to strings.

Next: Setting Up a React Project