Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 12 / Topic 6 of 6

key-driven remounts

key is how React decides whether an element at a given position is the same instance (update it, keep its state) or a different one (throw the old instance away, mount a fresh one). examples/06_key_driven_remount.jsx's NoteEditor keeps a draft of unsaved text; CartItemEditorBroken renders it with no key tied to the item being edited:

// examples/06_key_driven_remount.jsx (broken)
export function CartItemEditorBroken({ item }) {
  return <NoteEditor itemId={item.id} initialNote={item.savedNote} />;
}

Typing a draft note for item A, then re-rendering with item B in the same position, really leaves item B's editor showing item A's leftover draft (examples/06_key_driven_remount.test.jsx) - mountCount.value stays at 1, proving React genuinely reused the same component instance (and its state) across two unrelated items, because nothing told it not to. CartItemEditorFixed adds exactly one thing:

// examples/06_key_driven_remount.jsx (fixed)
export function CartItemEditorFixed({ item }) {
  return <NoteEditor key={item.id} itemId={item.id} initialNote={item.savedNote} />;
}

The identical scenario against this version really shows item B's editor starting clean, and mountCount.value really reaches 2 - proof that changing the key forced a genuine unmount-then-mount, not merely a prop update. This is memo's opposite move: memo exists to avoid unnecessary work by reusing an instance; a changed key exists to force a fresh one on purpose, exactly when reuse itself is the bug.

Done here? The practice set for Part 12 — including the solutions — is on the part page.

Search the guide