Index keys after list reordering
Click the first row, then Reverse. Predict the two row labels in order. What changes if you use key={item} instead?
Code Snippet
import { useState } from "react";
function Row({ item }) {
const [n, setN] = useState(0);
return <button onClick={() => setN(x => x + 1)}>{item}: {n}</button>;
}
export default function App() {
const [reverse, setReverse] = useState(false);
const items = reverse ? ["B", "A"] : ["A", "B"];
return <>
{items.map((item, i) => <Row key={i} item={item} />)}
<button onClick={() => setReverse(x => !x)}>Reverse</button>
</>;
}Expected Output & Explanation
Index keys: B: 1, A: 0
Item keys: B: 0, A: 1 With index keys the count belongs to position identity, so B inherits the first row’s count. Item keys let state follow the items as they move.
Module Context & References
React · Predict the behavior Trace state queues, stale snapshots, keys, effects and refs
Personal Notes · Markdown