React Lists: The `key` Prop

Unlock huge performance gains and prevent subtle bugs by mastering this fundamental React concept.

Lesson ProgressStep 1 of 8
  • Apple
  • Banana
  • Cherry
0 EXP

Hello! Let's explore one of React's most important concepts: rendering lists.

const data = ['Apple', 'Banana', 'Cherry'];

Rendering Lists with `.map()`

You can't render an array of data directly in React. Instead, you use the standard JavaScript `.map()` method to transform your array of data into an array of JSX elements.

const numbers = [1, 2, 3];
const listItems = numbers.map(number => <li>{number}</li>);
return <ul>{listItems}</ul>;

This is the fundamental pattern for rendering any dynamic list in React, whether it's a list of numbers, users, or to-do items.

System Check

Which array method is standard for transforming data into JSX lists?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

🔑
Key Provider

Correctly render a list with a `key` prop in the editor.

🏆
Stable Key Master

Correctly identify the best and worst types of keys.

✍️
Syntax Expert

Prove your mastery of `key` prop syntax.

Mission: Render a List with Keys

Given the `products` array, render an unordered list (`ul`) where each list item (`li`) displays the `product.name` and has the correct `key` prop.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Order the Keys

Drag these key types into order from **Best** (top) to **Worst** (bottom).

key={index}
key={item.id}
key={Math.random()}

Challenge: Complete the Syntax

Fill in the missing parts to correctly map over the `users` array.

{users.(user => (<li ={}>{user.name}</li>))}

Consult A.D.A.

Community Holo-Net

Keys in Practice: Beyond the Console Warning

Every React developer has seen it: the console warning about missing `key` props. It's tempting to "fix" it by just throwing in the array `index` and moving on. However, understanding why keys exist reveals one of React's most powerful optimization features: the **reconciliation algorithm**.

When a component's state or props update, React builds a new "tree" of elements and compares it to the previous one. This comparison is called "diffing". When React diffs a list of children, it uses the `key` prop to match children from the old tree with children in the new tree.

The `index` Anti-Pattern: A Case Study in Bugs

Let's see what happens when you use `index` as a key for a list that can be reordered or filtered.

Imagine a list of items where each item is a component that manages its own state (like a text input).

// ⚠️ ANTI-PATTERN: DO NOT DO THIS
const [items, setItems] = useState(['Apple', 'Banana']);

// ... user adds 'Cherry' to the *beginning* of the list ...

// Now items = ['Cherry', 'Apple', 'Banana']

return (
  <ul>
    {items.map((item, index) => (
      <li key={index}>
        {item} <input type="text" />
      </li>
    ))}
  </ul>
);
  • Before: React sees `key=0` ("Apple") and `key=1` ("Banana"). The user types "My note" into the input for "Apple".
  • After: React sees `key=0` ("Cherry"), `key=1` ("Apple"), and `key=2` ("Banana").
  • The Problem: React's diffing algorithm says: "The component with `key=0` used to be 'Apple', now it's 'Cherry'. I'll update it. The component with `key=1` used to be 'Banana', now it's 'Apple'. I'll update it."
  • The Bug: The component instances (and their internal state) are recycled. The `input` with `key=0` (which still contains "My note") is reused for "Cherry". The `input` for "Apple" (now `key=1`) is recycled from the old "Banana" component, so it's empty. The user's state has been incorrectly associated with the wrong item.

Stable Keys: The Correct Solution

The solution is to use a key that is **stable** (doesn't change for a given item) and **unique** (no two items have the same key). This is almost always a unique ID from your data.

✔️ Good Practice

const data = [
  { id: 'a', name: 'Apple' },
  { id: 'b', name: 'Banana' }
];

{data.map(item => (
  <li key={item.id}>
    {item.name}
  </li>
))}

Keys are stable and unique. React can track items perfectly.

❌ Bad Practice

const data = ['Apple', 'Banana'];

{data.map((item, index) => (
  <li key={index}>
    {item.name}
  </li>
))}

Keys are unstable. Reordering or filtering will cause bugs.

What About `Math.random()`?

Using `key=0.712228927493072` is even worse than using `index`. Because the key will be different *every single time* the component renders, React will think the *entire list* was destroyed and recreated from scratch. This forces React to destroy all DOM nodes and component instances, leading to terrible performance and the loss of all state (like text in inputs or focus).

Key Takeaway: Always use a stable and unique ID from your data as the `key`. This is the single most important rule for rendering lists in React. It ensures high performance, predictable behavior, and bug-free state management in dynamic lists.

React Lists & Keys Glossary

Key (`key`)
A special string attribute that must be included when creating lists of elements. It provides a stable identity for each element, allowing React to track additions, removals, and reorders.
Reconciliation
The process by which React updates the DOM to match the desired component state. When a component updates, React compares the new Virtual DOM tree with the old one and computes the minimal set of DOM
Diffing Algorithm
The algorithm React uses during reconciliation to compare two Virtual DOM trees. When comparing a list of children, the `key` prop is the primary hint it uses to match elements between the two trees.
Virtual DOM (VDOM)
A lightweight in-memory representation of the actual browser DOM. React creates a new VDOM tree on every render and "diffs" it against the previous one to calculate updates.
Stable Identity
The concept that a `key` for a specific piece of data (like a user) should be the same across all renders. A `user.id` is stable, whereas an array `index` is not if the array can be sorted or filtered.
Component State
Internal data managed by a component (e.g., text in an `input`, or whether a checkbox is ticked). React uses keys to preserve the state of component instances. Incorrect keys can cause state to be lost or mismatched.
Anti-Pattern
A common solution to a problem that is ineffective and likely to cause more problems. Using `index` or `Math.random()` as a `key` are classic React anti-patterns.

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of web development experts, who have years of experience teaching React and building robust and accessible web applications.

Verification and Updates

Last reviewed: October 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on the latest React specifications (React 18+) and is periodically reviewed to reflect industry best practices.

External Resources

Found an error or have a suggestion? Contact us!