Core Concepts

Lists and Keys

Render dynamic lists of data and understand why keys are essential for performance.

Rendering Lists

You can render lists of elements using JavaScript's .map() method inside JSX.

Keys

Keys help React identify which items have changed, been added, or removed. They should be unique among siblings.

Good keys:

  • Database IDs
  • Unique slugs or usernames

Bad keys:

  • Array indices (causes bugs when list order changes)
  • Random numbers (creates new keys on every render)

Key Rules

  • Keys must be unique among siblings (not globally)
  • Keys are not passed as props — use a different prop name if you need the value

Example

jsx
// Basic list rendering
function FruitList() {
  const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];

  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{fruit}</li>
      ))}
    </ul>
  );
}

// Better: use unique IDs as keys
function ProductList({ products }) {
  return (
    <div className="product-grid">
      {products.map(product => (
        <div key={product.id} className="product-card">
          <h3>{product.name}</h3>
          <p>{product.price}</p>
          <button>Add to Cart</button>
        </div>
      ))}
    </div>
  );
}

// Filtering and mapping
function TaskList({ tasks }) {
  const pending = tasks.filter(t => !t.done);

  return (
    <div>
      <h2>Pending Tasks ({pending.length})</h2>
      <ul>
        {pending.map(task => (
          <li key={task.id}>
            <strong>{task.title}</strong>
            <span> - Due: {task.dueDate}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}
Try it yourself — JSX