Lesson 21 / 25

Keys and Component Identity

Same position, same state; new key, fresh state.

React tracks components by position and key

React keeps a component's state as long as the same component type renders at the same position in the tree. That is why a draft typed for one recipient can survive when the recipient prop changes. Giving a component a different key tells React it is a different instance: the old one unmounts with its state and a fresh one mounts. Use this to reset state on purpose (a form per user id) instead of syncing state with effects.

State kept without a key, reset with one, run

I ran this with React 19.3 and react-dom 19.3 on Node.js 22, compiling JSX with esbuild 0.28. Browser-style examples use jsdom 29 as a fake DOM (imported from a small setup-dom.mjs file) and act() to apply updates. Without a key, the draft "Hi Asha" stays after switching the recipient to Ravi. With key set to the recipient, switching to Ravi mounts a fresh component and the draft is empty.

import "./setup-dom.mjs";   // test setup: jsdom provides a browser-like DOM in Node
import { useState, act } from "react";
import { createRoot } from "react-dom/client";

function Draft({ to }) {
  const [text, setText] = useState("");
  return <p data-to={to} onClick={() => setText("Hi " + to)}>{text || "(empty)"}</p>;
}
const root = createRoot(document.getElementById("root"));
await act(() => root.render(<Draft to="Asha" />));
await act(() => document.querySelector("p").click());
await act(() => root.render(<Draft to="Ravi" />));             // same position: state kept
console.log("without key:", document.querySelector("p").textContent);
await act(() => root.render(<Draft key="Asha" to="Asha" />));
await act(() => document.querySelector("p").click());
await act(() => root.render(<Draft key="Ravi" to="Ravi" />));  // new key: fresh component
console.log("with key   :", document.querySelector("p").textContent);

Output:

without key: Hi Asha
with key   : (empty)

Reset with key, not effects

Instead of an effect that clears state when an id changes, render the component with key={id}.

Quick check: What happens when a component's key changes?

  • Nothing
  • React unmounts it and mounts a new instance with fresh state
  • Only its CSS changes
  • React throws an error
Answer

React unmounts it and mounts a new instance with fresh state — Keys define identity.