What is the key prop in React and why does it matter?

The key prop helps React identify which list items changed, were added, or removed using array index as key causes subtle bugs.

React

Overview

When rendering a list, React needs a way to track which elements changed between renders. The `key` prop is a stable identifier for each list item. Without proper keys, React may re-use the wrong DOM nodes, causing unexpected UI bugs.

Key Points

  • •Key must be a stable, unique string or number among siblings in the same list.
  • •Keys are not passed to the component they are internal to React.
  • •Using array index as a key causes bugs when items are reordered, inserted, or deleted.
  • •Keys only need to be unique among siblings, not globally unique.
  • •When a key changes, React destroys the old component and mounts a new one useful for forcing a reset.

Examples

Correct: use a stable id from the data

tsx
const TodoList = ({ todos }: { todos: Todo[] }) => (
  <ul>
    {todos.map(todo => (
      <li key={todo.id}>{todo.text}</li>
    ))}
  </ul>
);

Wrong: index as key causes reorder bugs

tsx
// Avoid if items are reordered, React reuses components incorrectly
{todos.map((todo, index) => (
  <TodoItem key={index} todo={todo} />
))}

Input components, animation states, and focus will be applied to the wrong items after reorder.

Force-reset a component by changing its key

tsx
// Changing key destroys and remounts useful to reset state
<CommentForm key={postId} postId={postId} />

When postId changes, the form is completely reset (all local state cleared).

Pro Tip

If your data doesn't have a natural `id`, create one at data-generation time (e.g. with `crypto.randomUUID()`). Never generate keys inside the render function (`Math.random()`) a new key on every render forces a remount on every render.