zaro

How does React key work?

Published in React Component Keys 5 mins read

React keys are special string attributes that help React efficiently identify and track elements within a list, ensuring consistent and optimized UI updates. They are fundamental to React's reconciliation process, allowing the framework to determine exactly which items in a list have changed, been added, or removed.

Understanding React's Reconciliation

When a component's state or props change, React needs to update the browser's Document Object Model (DOM) to reflect these changes. This process is handled by React's reconciliation algorithm. Instead of simply re-rendering the entire DOM, React builds a virtual DOM tree and then compares it with the previous virtual DOM tree. This comparison identifies the minimal set of changes needed to update the actual DOM, making the process highly efficient.

The Role of the key Prop

This is where the key prop becomes crucial. React's key prop gives you the ability to control component instances. Each time React renders your components, it calls your functions to retrieve the new React elements that it uses to update the DOM. If you return the same element types, React attempts to keep those components and their associated DOM nodes around, even if all their props have changed.

A unique and stable key helps React accurately match a specific item in the old list to its corresponding item in the new list. It acts as a stable identifier for each element. This identification allows React to:

  • Preserve State: If an item's key remains the same across renders, React knows it's the same logical component instance, even if its position in the list changes. This allows the component to retain its internal state.
  • Optimize Performance: By identifying existing elements, React can reuse and reorder existing DOM nodes instead of unmounting and re-mounting them. This minimizes direct DOM manipulation, which is a costly operation.
  • Prevent Bugs: Without proper keys, especially when list items can be reordered, added, or removed, React might incorrectly reuse component instances, leading to strange UI behavior, display errors, or lost form input values.

Key Requirements: Unique and Stable

For keys to work effectively, they must meet two essential requirements:

  1. Unique within a list: Each key must be unique among its siblings within the same array. It doesn't need to be globally unique across the entire application.
  2. Stable across re-renders: The key for a particular item should remain the same from one render to the next. If a key changes for the same data item, React will treat it as a new component and unmount the old one, losing its state.

Why Using Index as a Key is Often Problematic

A common mistake is using an item's array index as its key. While this works for static lists that never change, it can cause issues when:

  • List items are reordered: If items are sorted or moved, their indices change. React sees the "new" index as a "new" key for potentially a "different" item, causing it to incorrectly re-render or reuse components.
  • Items are added/removed in the middle: Adding an item shifts the indices of all subsequent items. React then misidentifies existing items, potentially leading to state mix-ups.

Example of an Incorrect Key Usage (using index):

// Avoid this if list items can change order, be added, or removed
const numbers = [1, 2, 3];
<ul>
  {numbers.map((number, index) => (
    <li key={index}>{number}</li> // Problematic!
  ))}
</ul>

Example of Correct Key Usage (using a stable ID):

const todos = [
  { id: 'a1', text: 'Learn React' },
  { id: 'b2', text: 'Build a project' },
  { id: 'c3', text: 'Deploy to Netlify' },
];

<ul>
  {todos.map(todo => (
    <li key={todo.id}>{todo.text}</li> // Correct! 'id' is a stable, unique identifier.
  ))}
</ul>

When an item doesn't have a stable ID, you can generate one or use a library. However, if your list is truly static and will never be reordered or filtered, using the index as a key might be acceptable, but it's generally best practice to avoid it.

Benefits of Proper Key Usage

Using appropriate keys in your React lists leads to several significant advantages:

  • Reliable UI Updates: Ensures that the correct components are rendered for the correct data, preventing visual glitches and unexpected behavior.
  • Optimized Performance: Reduces unnecessary DOM manipulations by allowing React to reuse existing elements and their associated state.
  • State Preservation: Crucial for components that maintain internal state (e.g., form inputs, toggles) within a dynamic list.

For more in-depth information, refer to the official React documentation on lists and keys.

Key Concepts Summary

To summarize the difference between using and not using proper keys:

Aspect Without Proper Keys (e.g., index) With Proper Keys (stable, unique ID)
Identity Relies on element type and render position. Explicitly identifies each element in the list.
Re-ordering Can lead to incorrect component reuse and state bugs. Accurately reorders and reuses component instances.
Performance Less optimal; may unmount/remount existing DOM nodes. Optimized; reuses existing DOM nodes and preserves state.
State Often lost or misapplied when list items change position. Preserved for individual items as their key remains constant.