Lists & Keys
Keys provide unique stable identities to array elements so React can efficiently match, reorder, or delete DOM nodes.
Mental Model
"The Coat Check Ticket: When retrieving your coat, the attendant uses your unique ticket ID instead of guessing your coat size by appearance."
Interactive Engine Walkthrough
Reference Code Snippet
1function UserList({ users }) {
2 return (
3 <ul>
4 {users.map(user => (
5 // Key must be stable, unique, and predictable
6 <li key={user.id}>
7 {user.name}
8 </li>
9 ))}
10 </ul>
11 );
12}- 01.Keys must be unique among sibling elements in the same array.
- 02.Never use array indices as keys if items can be sorted, inserted, or filtered.
- 03.Keys help React maintain local component state across reorders and deletions.
01. Why Keys Matter
When React diffs two versions of a list, it needs a way to know which items have been moved, added, or deleted. Without a key, React simply updates the content of the existing DOM nodes in order (Index-based diffing), which can lead to massive performance issues or state bugs in components with internal state.
Reconciliation Strategy
02. The Index Anti-Pattern
Using the array index as a key is only safe if the list is static (never filtered, sorted, or reordered). If you shuffle a list using indices as keys, React will think the item at index 0 is the same "identity" even if the data is different, causing input values or animations to persist on the wrong items.
Expert Rule
"Keys don't need to be globally unique—they only need to be unique among their siblings. Always prefer IDs from your database or generated UUIDs over indices."