Changing a prop with or without a changing key
Click A: 0 to increment it, then click Switch. Compare the first button if the marked key is removed and the same steps are repeated after a fresh mount.
Code Snippet
import { useState } from "react";
function Counter({ label }) {
const [n, setN] = useState(0);
return <button onClick={() => setN(x => x + 1)}>{label}: {n}</button>;
}
export default function App() {
const [label, setLabel] = useState("A");
return <>
<Counter key={label} label={label} />
<button onClick={() => setLabel("B")}>Switch</button>
</>;
}Expected Output & Explanation
With key: B: 0
Without key: B: 1 A different key means a different component identity. Without key, the same type occupies the same position after the prop changes, so its state survives.
Module Context & References
React · Predict the behavior Trace state queues, stale snapshots, keys, effects and refs
Personal Notes · Markdown