Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 132 ยท Performance

Reconciliation and Keys in Depth

Understand how React decides to update, reset or remount a component - same type and position, the key prop, index keys, reordering, nested component definitions - with live effect logs.

Every time a component renders, React produces a fresh tree of elements describing what the screen should look like. It then has to work out what changed compared with the previous tree, so it can update the DOM as little as possible. That comparison process is called reconciliation.

You rarely think about it, until a text field loses what you typed, an animation restarts, or a list item keeps the wrong state after you sort. All of those are reconciliation at work, and they all come down to one question React asks again and again: is this the same component as before? This lesson gives you the exact rules, proves them with mount and unmount logs, and shows how to use the key prop on purpose. For the broader picture see How React Works and Lists and Keys.

The two rules

React compares the old and new element at each position in the tree, from the top down:

  1. Different type (<div> becomes <section>, or <Counter> becomes <Timer>): React throws the old subtree away. DOM nodes are removed, effect cleanups run, and all state in that subtree is destroyed. The new type is mounted from scratch.
  2. Same type: React keeps the existing instance and its state and just passes the new props. DOM nodes are updated in place. For components, the function is called again with the same hook state.

Position matters: "same place in the tree" means same parent, same index among siblings, unless a key says otherwise. State is not stored in your component function; it is stored by React at a position in the tree, and the component "owns" it only while it keeps being rendered at that position with that type.

The next example makes this visible. A Counter logs when it mounts and unmounts, and the app can render it either as a bare element or inside a wrapper.

Same type keeps state, different type resets it

Click the counter button twice, then tick "Tinted background": the background changes and the count stays at 2, with nothing logged. The element type did not change, only a prop did, so React updated the existing nodes. Now tick "Wrap in a section". The count jumps back to 0 and the console shows unmount A followed by mount A: div became section, so React discarded everything under it, including the Counter and its state, even though the Counter element itself looks identical.

The {wrapped ? <section>โ€ฆ</section> : <div>โ€ฆ</div>} pattern is the classic accidental reset. If you change a wrapper element conditionally, the children below it lose their state. Prefer changing attributes (className, style) over swapping the element type.

Keys: giving elements an identity

Inside a list, position alone is a weak identity: if an item is inserted at the top, every other item shifts by one position. The key prop is how you tell React "this is that same item as before, wherever it sits now".

JSX
{people.map((person) => (
  <Row key={person.id} person={person} />
))}

React matches old and new children by key first, then by type. A matched child keeps its state and DOM node, and is moved if its position changed. A new key mounts a new instance. A key that disappeared unmounts its instance.

Index keys: fine until you reorder

If you use the array index as the key, the identity becomes "the n-th row", not "this person". That is correct only if the list never gets reordered, filtered or inserted into. Here each row has a text input with its own state; the button reverses the list.

Index keys versus stable ids

Type first into Ada's box (the first row), then press "Reverse list" with the checkbox unticked. The names swap order, but first stays in the top box, which now belongs to Linus. React saw "key 0, key 1, key 2" before and after, so it kept each instance at its position and only updated the name prop; the typed text is state, and state stayed behind. Now tick "Use ids as keys", type into a row, and reverse again: the text travels with the person, because the key 1 identifies Ada's instance wherever she moves.

This is not only a cosmetic bug. Stale state in the wrong row can mean the wrong checkbox is ticked, or a draft message goes to the wrong person.

What makes a good key

  • Unique among siblings (not globally), and stable: the same item must get the same key on every render.
  • Prefer ids that come from your data (database ids, slugs). If items are created on the client, assign an id when you create them.
  • Index keys are acceptable for static lists that never change order and have no state.
  • Never use Math.random() or crypto.randomUUID() during render as a key: every render produces new keys, so every row is unmounted and remounted each time, which wipes state, loses focus and is slow.

The missing-key warning

If you map without a key, the development build tells you. This example is broken on purpose.

A list without keys (fails on purpose)

The list still renders, but the console reports Each child in a list should have a unique "key" prop. followed by Check the render method of App., pointing at the component that contains the map. It is only a warning because React falls back to index keys, which is exactly the situation the previous example showed to be risky. Warnings like this only appear in development builds; production stays silent, so fix them while you see them.

Keys are not only for lists: resetting state on purpose

Because a key is an identity, changing the key of a single element makes React treat it as a different component: the old one unmounts and a new one mounts with fresh state. This is the cleanest way to reset a component, and it is much better than an effect that copies props into state.

A profile form should start blank for each user. Without a key, React reuses the same Draft instance when you switch users and the typed text stays. With the key it is reset.

Reset a component by changing its key

Type hello for Ada and press "Grace" with the box ticked: the field empties and the console shows Draft unmounted for Ada then Draft mounted for Grace. Now untick the box. Removing the key remounts the component once (Draft unmounted for Grace, Draft mounted for Grace). Type hi, then switch back to Ada: the text hi stays in the field while the label changes to Ada, and nothing is logged, because the same instance was reused for a different user.

Resetting via key also resets everything below the component: child state, refs, effects and DOM nodes such as scroll position and focus.

Component definitions inside components

The "same type" rule compares function identity. A component defined inside another component is a new function on every render, so React sees a different type each time and remounts it on every parent render. It is one of the most damaging reconciliation mistakes, and it looks innocent.

A component defined inside a component

Increase both counters, then click "Re-render page". The module-level counter keeps its value. The inner one resets to 0, and the console shows CounterButton unmounted and CounterButton mounted for it. Define components at module level and pass data through props.

Fragments, order and element identity

  • A fragment has no DOM node but takes part in reconciliation. When you map to fragments you need the long syntax to attach a key: <Fragment key={item.id}>โ€ฆ</Fragment>. The short <>โ€ฆ</> cannot take props.
  • null, false and undefined still occupy a slot in the children array. {show && <Tip />} keeps the next sibling at the same position whether show is true or false, so siblings do not reset.
  • Keys are local to the parent array, not part of props: a component cannot read props.key, so pass the id again under another name if it needs it.
  • Reordering with keys moves existing DOM nodes instead of rebuilding them, so focus, scroll position and CSS transitions on the elements survive.

Pitfalls professionals know

  • Do not nest the same state-holding component under different element types depending on a condition, unless you want a reset.
  • Do not generate keys during render; generate ids when data is created.
  • A "remount storm" (a key or component identity changing on every render) is a common cause of lost input focus and slow lists. Mount and unmount logs, as used here, find it fast.
  • Use a changing key rather than useEffect(() => setState(initial), [id]) to reset state when a prop changes. Compare with You Might Not Need an Effect.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A component is rendered inside a <div> and then, after a state change, inside a <section> at the same place. What happens to its state?

    Different element types at the same position make React discard the old subtree, including all state of the components inside it.
  2. 2. You render rows with key={index} and then reverse the array. What is the likely symptom?

    With index keys, identity is the position. After the reversal each position keeps its instance and state, but receives another item's props.
  3. 3. How do you reset all of a component's state when a userId prop changes?

    A different key means a different identity, so React unmounts the old instance and mounts a fresh one with initial state.
  4. 4. Why is it a mistake to write function Inner() {...} inside another component and render <Inner />?

    Type comparison uses function identity. A new function each render means a different type each render, which destroys the subtree's state.
  5. 5. Which key is the best for items in a list that can be sorted and filtered?

    Keys must be unique among siblings and stable across renders. A data id satisfies both and follows the item when it moves.

Summary

  • Reconciliation compares the new element tree with the previous one: the same type at the same position keeps its state, a different type is unmounted and remounted.
  • Keys give list items an identity so state and DOM nodes follow the item when it moves; use stable ids, not indexes, for lists that change.
  • Changing an element's key is the clean way to reset a component and everything below it.
  • Components defined inside other components are new types on every render and are remounted constantly; define them at module level.
  • Swapping wrapper element types conditionally resets the subtree; change attributes instead.
  • Mount and unmount logs in effects make identity visible while you debug.

Next: Large Lists and Virtualization