Key Prop

A special React prop used to identify which items in a list have changed, been added, or removed, helping React optimize rendering performance.

Overview

The key prop is a special attribute in React that helps identify elements in a list. When rendering lists, React uses keys to determine which items have changed, allowing it to efficiently update only the necessary elements in the DOM. Using proper keys is crucial for performance and avoiding bugs in dynamic lists.

Example

javascript
// Good: Using unique, stable IDs as keys
function UserList({ users }) {
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>
          {user.name}
        </li>
      ))}
    </ul>
  );
}

// Bad: Using array index as key (anti-pattern when list can change)
function BadList({ items }) {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>  // Don't do this!
      ))}
    </ul>
  );
}

// Complex components with keys
function TodoList({ todos }) {
  return (
    <div>
      {todos.map(todo => (
        <TodoItem
          key={todo.id}
          todo={todo}
          onDelete={handleDelete}
        />
      ))}
    </div>
  );
}

// Generating keys when no natural ID exists
import { nanoid } from 'nanoid';

const items = data.map(item => ({
  ...item,
  id: nanoid()
}));

// Keys only need to be unique among siblings
function Blog({ posts }) {
  return (
    <div>
      {posts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <ul>
            {post.comments.map(comment => (
              <li key={comment.id}>{comment.text}</li>
            ))}
          </ul>
        </article>
      ))}
    </div>
  );
}

Key Points

  • Required when rendering lists
  • Must be unique among siblings
  • Should be stable (not change between renders)
  • Don't use array index if list can reorder
  • Helps React optimize re-renders

Learn More