The Analogy: A Stage Crew Resetting the Set From a Scene Photograph
A repertory theatre runs three different plays in a week, and between every act the stage must be reset. In the early days the director stood in the dark and called the changes by hand: "Move the armchair two feet left. No, the other chair. Take the lamp off. Put the rug back." The crew scrambled to follow a stream of individual orders, and if the director lost track of what was already on stage, props ended up in the wrong place or moved twice. The stage was changed by describing the motions, and nobody held a single trustworthy picture of where things were meant to end up.
The new stage manager works differently. Before each act she hands the crew a single photograph of exactly how the finished stage should look: every chair, lamp, and rug in its final position. She never lists the moves. The crew's whole job is to make the real stage match the photograph. They walk the set with the photo in hand, compare it against what is currently there, and change only the differences. If the armchair is already correct they leave it untouched; if the lamp moved, they move just the lamp.
That habit -- compare target against current, then touch only what differs -- is the entire idea. The photograph is a declaration of the desired end state, not a recipe of steps. Two crews handed the same photo arrive at the same stage even if they start from different set-ups, because the target is fixed and the work is derived from the gap. To pair things up quickly the crew relies on small tags taped to each large prop, "chair A", "chair B", so they can tell at a glance whether the chair in the photo is the same chair already on stage or a different one that must be carried on.
The method fails the moment those identity tags are missing or unreliable. If two chairs look alike and carry no tags, the crew cannot tell whether the chair in the new photo is the one already present or a replacement, so they either drag both off and bring fresh ones on (wasteful and slow) or, worse, redecorate the wrong chair. Hand the crew two photographs that each claim to be the current target and they freeze, unsure which is real. Every failure here traces back to the same two roots: no stable identity for the things being compared, or more than one competing source of truth for what the target is.
Syntax or Core Structure
React works exactly like the stage manager. You never write the steps that mutate the screen. You write a component -- a function that takes inputs (props and state) and returns a description of what the UI should look like for those inputs. React compares your new description against the previous one and changes only the differences on the real page. JSX is the notation for that description: it looks like HTML but is ordinary JavaScript underneath.
function Greeting({ name, unread }) {
return (
<header>
<h1>Hello, {name}</h1>
<span>{unread} unread</span>
</header>
);
}
The returned markup is not a string and not the real page; it is a plain tree of objects describing the target. To see that the output is a pure function of the inputs, we can model the same idea in plain JavaScript: a component returns a node tree, and rendering folds that tree down to text. Nothing here touches a browser, so the result is fully determined by the inputs.
function Greeting({ name, unread }) {
return { tag: "header", children: [
{ tag: "h1", children: ["Hello, " + name] },
{ tag: "span", children: [unread + " unread"] },
] };
}
function toHtml(node) {
if (typeof node === "string") return node;
const inner = node.children.map(toHtml).join("");
return "<" + node.tag + ">" + inner + "</" + node.tag + ">";
}
console.log(toHtml(Greeting({ name: "Ada", unread: 3 })));
Output:
<header><h1>Hello, Ada</h1><span>3 unread</span></header>
Call the same function with the same props and you get the same tree every time; that predictability is what lets React treat the previous and next descriptions as two photographs to diff.
Technical Depth: From JSX to a Reconciled Tree
JSX is sugar for function calls
Every JSX tag compiles to a plain function call that builds one node of the description tree. Understanding the desugaring removes the magic: there is no template language, only JavaScript expressions.
| JSX you write | What it compiles to |
|---|---|
<h1>Hi</h1> | createElement("h1", null, "Hi") |
<a href="/x">Go</a> | createElement("a", props, "Go") |
<Box>{n}</Box> | createElement(Box, null, n) |
<br /> | createElement("br", null) |
Because the children are ordinary expressions, anything valid in JavaScript is valid inside the braces: arithmetic, function calls, and array mapping. What you cannot put there is a statement such as an if or a for loop, since those do not evaluate to a value.
Declarative beats imperative because the gap is computed for you
| Concern | Imperative DOM code | Declarative React |
|---|---|---|
| What you write | Steps that mutate nodes | The target for the data |
| Who computes the changes | You, by hand | The reconciler |
| Risk of stale UI | High: easy to miss a branch | Low: re-derived from data |
| Testability | Needs a live DOM | Pure input to output |
Reconciliation pairs children by key
When the description changes, React walks the old and new child lists and pairs nodes by their key (the identity tag from the analogy), then emits the minimal set of mount, update, and unmount operations. We can compute that same plan as a pure function.
function plan(prev, next) {
const prevText = new Map(prev.map((n) => [n.id, n.text]));
const nextText = new Map(next.map((n) => [n.id, n.text]));
const ops = [];
for (const [id, text] of nextText) {
if (!prevText.has(id)) ops.push("mount #" + id);
else if (prevText.get(id) !== text) ops.push("update #" + id);
}
for (const [id] of prevText) {
if (!nextText.has(id)) ops.push("unmount #" + id);
}
return ops;
}
const before = [{ id: 1, text: "Milk" }, { id: 2, text: "Eggs" }];
const after = [{ id: 1, text: "Milk" }, { id: 3, text: "Bread" }];
console.log(plan(before, after).join(", "));
Output:
mount #3, unmount #2
Item 1 kept its key and its text, so it produces no work at all; only the genuinely new row is mounted and the departed row unmounted. Give every list item a stable key and React pairs them correctly. Use the array index as the key and a removal from the middle shifts every later key by one, so React concludes almost every row changed -- the exact "the chairs have no reliable tags" failure from the analogy.
Rendering a list and a condition with expressions
Because JSX braces hold expressions and never statements, a list is written as items.map(...) and a choice is written as a ternary or a logical &&. Modeled as pure functions over data, both are ordinary array and boolean operations with no framework magic.
function list(items) {
return items
.map((it) => (it.done ? "[x] " : "[ ] ") + it.label)
.join("\n");
}
const todos = [
{ label: "Write JSX", done: true },
{ label: "Add keys", done: false },
];
console.log(list(todos));
console.log(todos.length > 0 ? "has items" : "empty");
Output:
[x] Write JSX
[ ] Add keys
has items
The .map call builds one child per item and the ternary picks between two descriptions. This is also why an empty list needs no special case: mapping an empty array yields no children, and the guard expression simply selects the "empty" branch. Keeping these as plain expressions is what lets you unit-test the rendering logic without a browser in sight.
Components compose by nesting descriptions
A parent embeds a child by placing its tag in the returned tree; the child's description becomes a subtree of the parent's. Composition is just function results nested inside function results.
function Tag({ text }) {
return { tag: "em", children: [text] };
}
function Card({ title, label }) {
return { tag: "div", children: [
{ tag: "h2", children: [title] },
Tag({ text: label }),
] };
}
console.log(toHtml(Card({ title: "React", label: "UI" })));
Output:
<div><h2>React</h2><em>UI</em></div>
The parent does not care how Tag builds its subtree; it only places the returned node. A whole page is one root component with the rest nested inside, each responsible for its own slice of the photograph. Because each component is testable on its own, you can verify a leaf's output in isolation and trust that nesting it changes nothing about how it renders.
Real World Example: An Inbox Header That Trusts a Cached Count
Here is a slice of a notification center, written the way beginners often structure it. The view is a pure function of state: given the inbox state it returns the text to show. Notice that the state carries an unreadCount field alongside the actual messages array, and the badge reads that cached number.
function badge(count) {
return count > 0 ? " (" + count + ")" : "";
}
function renderInbox(state) {
const shown = state.messages.filter(
(m) => state.filter === "all" || !m.read
);
const rows = shown.map(
(m) => (m.read ? " " : "* ") + m.from + ": " + m.subject
);
const realUnread = state.messages.filter((m) => !m.read).length;
return [
"Inbox" + badge(state.unreadCount),
...rows,
"-- " + shown.length + " shown, " + realUnread + " actually unread",
].join("\n");
}
const state = {
filter: "unread",
unreadCount: 3,
messages: [
{ id: 1, from: "Ops", subject: "Deploy done", read: true },
{ id: 2, from: "Ada", subject: "Lunch?", read: false },
{ id: 3, from: "Billing", subject: "Invoice", read: false },
],
};
console.log(renderInbox(state));
Output:
Inbox (3)
* Ada: Lunch?
* Billing: Invoice
-- 2 shown, 2 actually unread
The render function is honest and declarative: every line it returns is derived from its argument, so given this state it always prints these four lines. The rows and the footer are computed straight from messages, which is why the footer correctly reports two unread. Read top to bottom, the structure is the stage-manager photograph: describe the finished view for this data and let the caller paint it.
The badge tells a different story. It reads state.unreadCount, a number stored separately from the messages, and that number says 3 while the list plainly contains two unread items. The two disagree because unreadCount is derived data frozen into state: when message 1 was marked read, someone flipped its read flag but forgot to decrement the cached counter. The single source of truth (the messages) and its cached summary have drifted apart.
This is the real design flaw in the code above, and it is among the most common bugs in React apps: storing a value in state that could have been computed from other state. Every place that can write messages now carries a second obligation to keep unreadCount in step, and the moment one path forgets, the interface lies. The footer shows the fix by example: it derives the count on the spot with filter(...).length, so it cannot drift.
The limits are worth stating plainly. This model prints text rather than mounting real DOM, so it deliberately ignores event handling, focus, and asynchronous loading, all of which a live inbox needs. It also assumes messages is already sorted and small enough to filter on every render; a real client would paginate and memoize the derivation. But the core lesson, derive rather than duplicate, holds at any scale.
Common Mistakes
- Returning sibling elements with no wrapper: A component must return a single root. Wrap siblings in a parent element or a
<>...</>fragment, or the JSX will not parse. - Using the array index as
key: For any list that can reorder, insert, or delete, an index key mispairs rows on the next render. Use a stable id drawn from the data instead. - Putting statements inside JSX braces: The braces take an expression, not a statement. An
ifor aforwill not compile; use a ternary, a logical&&, or a.mapcall. - Storing derived data in state: This is the inbox
unreadCountbug. If a value can be computed from existing state or props, compute it during render rather than caching a copy that can drift. - Mutating props: Props are read-only inputs from the parent. Assigning to a field of
propsinside a child breaks the one-way data flow and is ignored or throws under strict checks. - Writing
classandforin JSX: The attributes areclassNameandhtmlFor, becauseclassandforare reserved words in JavaScript. - Confusing a component with a DOM node: A component returns a description; the browser node is what React paints from it. Logging the return value shows objects, not finished HTML.
- Lowercasing a component name in JSX:
<greeting />is treated as an unknown HTML tag, so nothing renders; component tags must start with a capital letter, as in<Greeting />. - Assuming JSX runs like a script: It evaluates to a value that React renders when it chooses. Side effects written inline run at surprising times, so keep the render body pure.
Best Practices
- Keep components small and name them as nouns for the thing they render, such as
GreetingorInboxHeader. - Make render a pure function of props and state, and push side effects into effects or event handlers.
- Give every list item a stable, data-derived
key(an id), never the array index. - Derive values during render instead of caching them in state, so a single source of truth cannot drift.
- Treat props as read-only; to change data, lift it into state owned by an ancestor.
- Destructure props in the function signature so a component's inputs are self-documenting.
- Co-locate each component with the smallest piece of state that drives it.
- When behavior confuses you, mentally desugar the JSX into
createElementcalls and read it as plain JavaScript.
Practice Exercises
- Extend the
Greetingnode-tree example with a<footer>child, hand-trace the newtoHtmlresult, then run it to confirm your trace matches. - Add a
"reorder #id"case toplanthat fires when an item keeps its key but changes index, and test it on a two-item list whose order is swapped. - Remove
unreadCountfrom the inbox state and changebadgeto take the messages array, then verify the header and footer agree for several inputs. - Write only the signature and returned tree of a
RadioListcomponent for a keyed list of options, and note which field you would pass as each item'skey.