Back to Pathway
fundamentalsbeginner

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 Simulation

Fiber Reconciliation Topology
Lists & Keys
ChildComponent

Executable Code Snippet

Component.jsx
JSX / React 19
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}
Technical Takeaways & Best Practices
  • 01.Component re-renders are triggered by state or prop changes.
  • 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
  • 03.Automatic batching optimizes multiple state updates into a single render cycle.

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

No Key
Re-render All
vs
Unique Key
Move Node

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."