⚛️ React Q21 / 113

What is key in React list rendering?

AI-Powered Answer ✓ Answered

`key` is a special string attribute you need to include when creating lists of elements in React. It helps React identify which items have changed, are added, or are removed, significantly impacting performance and correctness of your applications.

What is `key`?

In React, when rendering a list of components or elements, each item requires a unique key prop. This key acts as a stable identity for a component in the list. It helps React efficiently update the UI by allowing it to uniquely identify each element in a collection, even if the order or content of the collection changes.

Why are `keys` important?

React uses the key prop during its reconciliation process. When a list is re-rendered, React compares the new list with the old list. By having a unique key for each list item, React can accurately determine if an item is new, updated, or removed, rather than re-rendering the entire list or incorrectly updating existing elements. This leads to improved performance and prevents potential bugs related to incorrect component state or UI updates.

  • Efficient Updates: React can quickly identify changes and make minimal DOM manipulations.
  • Correct Component State: Ensures that component instances maintain their state correctly across re-renders, especially when items are reordered or filtered.
  • Avoidance of Bugs: Prevents issues where the wrong data might be associated with a specific UI element if items shift position without proper identification.

Rules for `keys`

There are two fundamental rules for keys in React lists:

  • Keys Must Be Unique: Each key within the same list of siblings must be unique. It doesn't need to be globally unique across the entire application, only among its siblings.
  • Keys Must Be Stable: A key should ideally be permanent and not change between re-renders for the same list item. If a key changes, React will treat the component as a new component, unmounting the old one and mounting a new one, which can lead to performance degradation and loss of component state.

Best Practices for `keys`

  • Use Stable IDs from Data: Whenever possible, use a stable, unique ID coming from your data source (e.g., item.id from a database).
  • Avoid Using Index as Key: Using an item's index in the array (index) as a key is generally discouraged if the list items can change order, be added, or removed. It can lead to unpredictable behavior and performance issues. However, it's acceptable if the list is static and will never change.
  • Do Not Use Math.random(): Never use Math.random() for keys as it generates a new key on every render, violating the stability rule and causing performance problems and state loss.

Example

jsx
import React from 'react';

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}> { /* Using a unique ID from the todo object */ }
          {todo.text}
        </li>
      ))}
    </ul>
  );
}

// Example of usage:
// const myTodos = [
//   { id: 'a1', text: 'Learn React' },
//   { id: 'b2', text: 'Build a project' },
//   { id: 'c3', text: 'Deploy to Netlify' }
// ];
// <TodoList todos={myTodos} />

In this example, each todo item has a unique id which is used as the key. This ensures that React can efficiently identify and re-render the correct <li> elements even if the todos array changes (e.g., items are added, removed, or reordered).