← Back to Chapters

React Lists & Keys

?️ React Lists & Keys

⚡ Quick Overview

In React, lists are created from arrays using JavaScript’s map() function. Each rendered item must include a unique key so React can efficiently update only the elements that change instead of re-rendering the entire list.

? Key Concepts

  • Lists are generated using map().
  • Each item requires a unique key.
  • Keys help React track changes in collections.
  • Indexes should only be used as a last resort.

? Syntax & Theory

The map() method transforms an array into JSX elements. React uses the key attribute to detect which items are added, removed, or updated.

? View Code Example
// Rendering a list of strings using map()
function NameList() {
  const names = ["Alice", "Bob", "Charlie"];

  return (
    <ul>
      {names.map((name) => (
        <li key={name}>{name}</li>
      ))}
    </ul>
  );
}
? View Code Example
// Always provide a unique key when rendering items
{items.map((item) => <li key={item.id}>{item.name}</li>)}
? View Code Example
// Rendering list from array of objects
function ProductList() {
  const products = [
    { id: 1, name: "Laptop", price: 60000 },
    { id: 2, name: "Phone", price: 25000 },
    { id: 3, name: "Tablet", price: 30000 }
  ];

  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>{p.name} — ₹{p.price}</li>
      ))}
    </ul>
  );
}
? View Code Example
// Rendering components dynamically
function Product({ name, price }) {
  return <li>{name} — ₹{price}</li>;
}

function ProductList() {
  const items = [
    { id: 1, name: "Keyboard", price: 1500 },
    { id: 2, name: "Mouse", price: 800 },
    { id: 3, name: "Monitor", price: 12000 }
  ];

  return (
    <ul>
      {items.map((item) => (
        <Product key={item.id} name={item.name} price={item.price} />
      ))}
    </ul>
  );
}
? View Code Example
// Using index as key (not recommended for dynamic lists)
{items.map((item, index) => (
  <li key={index}>{item}</li>
))}

?️ Live Explanation

React uses key values internally to determine what has changed in a list. Stable keys allow DOM updates to be faster and prevent unexpected UI behavior when items are added, removed, or reordered.

? Tips & Best Practices

  • Always use stable IDs for key values.
  • Avoid using index as a key when list order can change.
  • Keep list rendering logic simple and readable.
  • Keys are not passed as props to components.

? Try It Yourself

  1. Create a list of student names and render them.
  2. Convert a list of products into components.
  3. Experiment by reordering items with and without keys.
  4. Test conditional list rendering with empty arrays.

Goal: Master rendering dynamic lists using map() and optimize UI updates with proper keys.