Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  React
Handbook~16 min readFrontendworked math + runnable code
The React Handbook

Describe it.
React diffs it.

React's promise is that you write your UI as if you rebuild the whole thing on every change — no manual DOM surgery, just "here's what it should look like now." The trick that makes that fast is reconciliation: React builds a lightweight virtual DOM, diffs it against the previous one, and applies only the minimal real changes. And the humble key is what tells that diff which list items are "the same" across renders. Get keys right and React reuses elements cheaply; get them wrong (hello, array index) and you get baffling bugs. This handbook is that diff, made runnable.

01

Declarative UI

Before React, updating a UI meant imperative DOM surgery: find this node, change its text, add that child, remove the other — and keep it all consistent with your data by hand, which is where bugs breed. React's core idea is declarative: your components are functions of state that return a description of what the UI should look like right now. You never touch the DOM; you just say "given this state, here's the tree."

That description is the virtual DOM — plain JavaScript objects, cheap to create and compare. On every state change, React re-runs your components to build a new virtual tree, and now it faces a question: the real DOM currently matches the old tree, so what's the smallest set of real changes to make it match the new one? Answering that efficiently is reconciliation, and it's the engine that lets you program as if you rebuild everything while React quietly does almost nothing. The whole framework rests on this: describe the target, let React compute the diff, and keep the expensive real-DOM mutations to a minimum.

The one-sentence version

You return a new virtual DOM on every render; React reconciles it against the previous tree to apply minimal real changes — and it matches list items by key: same key = reuse in place, new key = mount, missing key = unmount.

02

Reconciliation

Reconciliation is the diffing process. React holds the previous virtual tree, builds a new one when state changes, and walks both to find what actually differs — then applies only those changes to the real DOM. The reason this is a win is a cost asymmetry: creating and comparing plain objects in memory is cheap, while mutating the real DOM (and triggering layout/paint) is expensive. So React does the cheap thing a lot to avoid doing the expensive thing.

To keep the diff fast, React uses heuristics rather than a perfect (and slow) tree-diff. Two matter most. First, different element types produce different trees: if a node changes from a <div> to a <span>, React doesn't try to reconcile them — it tears down the old subtree and builds the new one. Second, and the focus of this handbook: lists are matched by key. When React reconciles a list of children, it doesn't compare them purely by position — it pairs old and new items by their key prop, which is how it knows that an item which moved is still the same item and should be reused rather than rebuilt. Everything about efficient list updates flows from that key-matching step.

03

Keys are identity

A key is the identity React assigns to a list item so it can track that item across renders. During list reconciliation, React pairs old and new children by key and takes one of three actions:

Reconciling a list by key
key in bothReuse — same item; update it in place, keep its DOM node and component state.
key new onlyMount — a fresh element is created and inserted.
key old onlyUnmount — the element is removed and destroyed.
reorderSame keys, new order → everything reused (moved), zero mount/unmount.

The payoff of stable keys is that reordering a list is nearly free: if the keys are the same, React knows every item still exists and just moves the existing DOM nodes, preserving their state (a focused input stays focused, a running animation keeps running). Inserting one item mounts exactly one node; removing one unmounts exactly one; the rest are untouched. This is why React requires a key on list items — it's not a formality, it's the identity information the diff needs to reuse elements instead of blowing them away. Give it a stable, data-derived key (a database id, a slug) and reconciliation does the minimum possible work. The next sections show what happens when the key is wrong.

04

The diff math

Diffing a list by key partitions the items into three sets — reused (in both), mounted (new only), unmounted (old only):

reused = new ∩ old    mounted = new ∖ old    unmounted = old ∖ new

Real-DOM cost is the mounts + unmounts; reused items only update in place. So a pure reorder (same key set) costs 0 mount/unmount ops — everything is reused.

The expensive operations are exactly the mounts and unmounts; a stable key set makes a reorder free, an index key makes it costly and buggy:

dom_ops  =  |mounted| + |unmounted|     reorder with stable keys ⟹ 0     index key ⟹ wrong reuse (state leaks)

Reorder ["a","b","c"]→["c","b","a"]: same keys, 0 DOM ops. The runnable version below computes the diff, the DOM-op cost, and detects when an index key breaks.

RUN IT YOURSELF

Reconciliation by key

React reconciles a list by matching items by key: a key in both the old and new list means reuse the element in place (keeping its DOM node and state); a key only in the new list mounts a new element; a key only in the old list unmounts one. The real cost is the mounts plus unmounts — so a pure reorder with stable keys costs zero. Using the array index as a key breaks this: on a prepend or reorder, an index points at different data than before, so React reuses the wrong element and state leaks to the wrong row. Change the key lists and watch the diff and the cost.

CPython · WebAssembly
05

The index-key trap

The most common React bug of all comes from using the array index as the key — items.map((item, i) => <Row key={i} …/>). It looks harmless and often works in demos, because the index is unique. The problem is that an index describes a position, not an identity. When the list is reordered, filtered, or gets an item inserted at the front, positions shift but the index keys don't move with the data.

Concretely: prepend an item and the row that was at index 0 is now at index 1 — but React still sees key=0 at position 0 and thinks it's the same element as before, so it reuses that DOM node in place with new data. Any state living in that element — the text typed into an input, which checkbox is checked, a focus ring, an in-progress animation — stays with the position instead of moving with the item. You type into the first row, insert a row above it, and your text is now attached to the wrong entry. These bugs are maddening precisely because the render looks right and only the state is wrong. The runnable model above detects exactly this: when position i's identity changes while its index key stays the same, React's reuse is silently incorrect. Index keys are safe only for a static list that never reorders, filters, or inserts anywhere but the end — otherwise, use a stable unique id from your data, and the whole class of bug disappears.

06

Pitfalls

Beyond the index-key trap, the biggest reconciliation-adjacent pitfall is unnecessary re-renders. When a component's state changes, React re-renders it and its children by default, rebuilding their virtual trees (then reconciling). That's usually cheap, but for expensive subtrees it adds up — and a common cause is passing a freshly-created object or function as a prop on every render, which makes memoized children think something changed. The tools are React.memo (skip re-rendering a child whose props are unchanged), useMemo/useCallback (keep the same reference across renders), but reach for them when you've measured a problem, not reflexively.

Two more. Keys that aren't stable: a key generated fresh each render (key={Math.random()}) is as bad as no key — every item looks new, so React unmounts and remounts the whole list every render, destroying state and performance. Keys must be stable and tied to the item's identity. And treating the virtual DOM as inherently fast: it isn't magic — it's a diffing buffer whose whole job is to minimize real-DOM work, and you can defeat it (with unstable keys, giant unmemoized trees, or churny props) into doing more work than hand-written DOM code. Respect what it's doing and it's a huge win; fight it and it's overhead. The whole handbook reduces to the mental model worth keeping: you describe the UI, React diffs your description against the last one and applies the minimum, and keys are the identities that let that diff reuse elements — so give every list item a stable, data-derived key and reconciliation does almost no work at all.

Worth knowing

Give list items a stable, data-derived key (never the array index for dynamic lists, never a random value). Reach for React.memo/useMemo/useCallback only when you've measured an expensive re-render. The virtual DOM minimizes real-DOM work — it isn't automatically fast, and unstable keys defeat it.

By the numbers

Worked example: prepending one row, index keys vs id keys

A todo list renders ["Buy milk", "Call Sam"] (ids b, c), each row with an uncontrolled <input> for a note. You type draft into the Buy milk row. Then a new item, Ask Lee (id a), is prepended. Trace what React pairs at each position under each key choice.

PositionNew itemkey={i}: paired withYou seekey={item.id}: paired withYou see
0Ask Leekey 0, the old Buy milk node: reused, label updatedAsk Lee next to draft: wrong rowkey a is new: mountAsk Lee, empty note
1Buy milkkey 1, the old Call Sam node: reused, label updatedBuy milk, empty note: the draft is gone from itkey b: same node, untouchedBuy milk next to draft
2Call Samkey 2 is new: mountCall Sam, empty notekey c: same node, untouchedCall Sam, empty note
Total1 mount + 2 label updatesState is attached to the wrong data1 mount (inserted at the top), 0 updatesEvery note stays with its item

Index keys did more DOM work (two text updates on top of the mount) and still got the answer wrong, because the typed text lives in the DOM node at position 0 and React kept that node at position 0. The page’s index_key_breaks(["b","c"], ["a","b","c"]) returns True for exactly this case. Scale it up: prepend to 1,000 rows with index keys and every one of the 1,000 existing positions gets new props, plus one mount at the end. With id keys it is one mount.

Trade-offs

Complexity and cost: what each update costs the reconciler

Here n is the number of children, or nodes in the tree. A generic minimal tree diff is about O(n³). React gets to O(n) by using the two heuristics on this page: a different element type means a new subtree, and list children are matched by key.

CaseTimeSpaceWhy
Re-render a tree of n nodesO(n) diffO(n): the current tree and the new oneCheap per node. The cost that matters is the real-DOM work the diff decides on.
Keyed list, items changedO(n): unmatched old children go into a map by keyO(n) for the mapEach new child finds its old match in O(1).
Reorder, stable keysO(n) diff; 0 mounts, 0 unmounts, some movesO(1) extra DOMMoving the first of 1,000 rows to the end moves 1 node. Moving the last row to the front moves 999, because React keeps old nodes whose old index only rises and moves the rest.
Prepend, index keysO(n) prop updates + 1 mountEvery row re-rendersEach position now holds different data, as in the example above.
Prepend, id keys1 mount, inserted before the first rowO(1) DOMThe other n nodes are reused untouched.
key={Math.random()}n unmounts + n mounts, every renderAll state lostNo key ever matches, so the whole list is rebuilt.
Element type changes (div to section)Unmount + mount the whole subtreeAll state below is lostReact does not compare across types; it rebuilds.

The page’s dom_ops counts mounts plus unmounts, which is the expensive part. Moves are a separate, cheaper cost that depends on which items moved, as the reorder row shows.

In the wild

Where this shows up in production and interviews

  • Chat and feed lists

    Loading older messages prepends to the top of a list, which is the exact case in the worked example. Key messages by their server id. A temporary client id for an unsent message has to stay as its key after the send, or the row remounts when the server id arrives.

  • Resetting state on purpose

    Since a new key means unmount and mount, <ProfileForm key={userId} /> is the idiomatic way to give a form fresh state when the user switches. The React docs recommend this over an effect that clears every field.

  • Forms with dynamic rows

    Invoice line items and survey questions that can be added, removed or dragged into order are where index keys cause bugs people actually see: a quantity typed into one line shows up on another after a delete. Generate an id when the row is created and keep it.

  • The interview question

    “Why does React need keys?” A strong answer covers reuse, mount and unmount, why index keys leak state on insert, and the fact that keys only need to be unique among siblings. Bonus: explain how a key can be used to force a remount.

Self-check

Check yourself

A list keyed by index has a checkbox per row. You tick row 0, then filter out the first item. Which row shows the tick?

The new row 0, which is the item that used to be second. Key 0 still exists, so React reuses that DOM node, and the checkbox’s checked state stays with the position. With id keys, the ticked item’s node is unmounted along with it.

You wrap a list item’s contents in a <section> instead of a <div>. A user had typed into an input inside it. What happens on the next render?

The input is emptied. A different element type means React tears down the old subtree and mounts a new one, so component state and DOM state below that point are gone, even though the keys did not change.

Rows ["a","b","c"] become ["c","a","b"] with stable keys. How many mounts, unmounts and moves?

0 mounts and 0 unmounts. Every key is present in both lists. React keeps c in place (old index 2), then moves a and b, whose old indexes 0 and 1 are below 2. That is 2 moves. All three nodes keep their state.

Is key={i} ever fine?

Yes, when the list is static or only ever grows and shrinks at the end. Then position and identity never come apart, so index keys pair each node with the same data every render. The moment you insert at the front or middle, reorder, or filter, use a stable id.

Frequently asked

Quick answers

What is reconciliation?

React diffs a new virtual DOM tree against the previous one and applies only the minimal real-DOM changes needed to match it.

What is the virtual DOM?

A cheap in-memory description of the UI that React diffs against the last render — a buffer that lets it minimize expensive real-DOM mutations.

Why do lists need keys?

Keys are the identity React uses to match list items across renders — reuse on match, mount on new, unmount on gone — so it can move elements instead of rebuilding them.

Why is index-as-key bad?

An index is a position, not an identity; on reorder or insert, React reuses the wrong element and state leaks to the wrong row. Use a stable data id.

Finished this one? 0 / 209 Handbooks done
NextThe React Interview Handbook Next on the “The languages you ship in” ladder · rung 4 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.