React Lists & Keys: Complete Beginner’s Guide with Examples

In real-world applications, you often need to display multiple items dynamically:

  • List of users

  • Product catalog

  • Todo list

  • Messages or notifications

In React, this is handled using lists and keys.

  • Lists allow you to render multiple elements efficiently.

  • Keys help React identify which items changed, added, or removed.

Think of keys as unique IDs for elements — without them, React can’t track updates efficiently.

Rendering Lists with .map()

The most common way to render lists in React is using JavaScript’s .map() function.

function NumberList() {
  const numbers = [1, 2, 3, 4, 5];
  return (
    <ul>
      {numbers.map((number) => (
        <li key={number}>{number}</li>
      ))}
    </ul>
  );
}

Output:

 
1
2
3
4
5

Why Are Keys Important?

Keys help React identify which items have changed, been added, or removed.

  • Without keys, React re-renders the entire list, which is inefficient.

  • Keys must be unique and stable among siblings.

 
// Correct
<li key={number}>{number}</li>

// Wrong: Using index as key (only for static lists)
<li key={index}>{number}</li>

Best practice: Use a unique ID from data instead of the array index, especially if the list can change.

Rendering Dynamic Objects

const users = [
  { id: 1, name: "John" },
  { id: 2, name: "Sara" },
  { id: 3, name: "Mike" }
];

function UserList() {
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}
  • user.id is used as the key.

  • This ensures React can track each user efficiently.

Example: Todo List

import { useState } from "react";

function TodoApp() {
  const [todos, setTodos] = useState([
    { id: 1, task: "Learn React" },
    { id: 2, task: "Build a project" },
    { id: 3, task: "Read documentation" }
  ]);

  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.task}</li>
      ))}
    </ul>
  );
}

Dynamic list updates are easy when each item has a unique key.

Keys Best Practices

RuleExplanation
Unique among siblingsEach key must be unique in the list it belongs to.
StableDo not use random numbers or array indexes if items can be reordered.
Use IDs if availableAlways prefer a unique property from data like id.
Avoid duplicate keysDuplicate keys can cause UI bugs and unpredictable behavior.

Common Mistakes

  1. Using index as key in a dynamic list → can cause bugs when items are added/removed.

  2. Forgetting keys → React logs “Each child in a list should have a unique key”.

  3. Using non-unique values → leads to inefficient re-rendering.

FAQ

Q1: Can I use array index as key?
 Only for static lists that never change. Otherwise, use unique IDs.

Q2: What happens if I don’t use keys?
 React logs a warning and may re-render the entire list unnecessarily.

Q3: Can keys be strings?
 Yes, keys can be strings or numbers, as long as they are unique and stable.