Labs ICT
โญ Pro Login

Lists and Keys

Rendering collections of data.

Rendering Lists

You've got an array of data โ€” maybe a list of users, products, or tasks. How do you show them on screen? With the map() method. It takes each item in the array and transforms it into something React can render. It's the bread and butter of displaying dynamic content.

Just like you'd use a loop in plain JavaScript, you use map in React to loop through data and create a component for each item. Each component gets its own data, and React puts them all on the screen for you.

Why Keys Matter

When you render a list, React needs to know which items are new, which moved, and which were removed. That's where keys come in. A key is a unique identifier for each item in your list. Without them, React gets confused about what changed.

Think of keys like name tags at a party. If everyone wore the same name tag, you'd have no idea who was who. Keys let React keep track of each item efficiently. Always use them when rendering lists.

function TodoList() {
  const todos = [
    { id: 1, text: "Learn React" },
    { id: 2, text: "Build a project" },
    { id: 3, text: "Deploy to production" },
  ];

  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}
Try it Yourself โ†’

Choosing the Right Key

The best key is a unique ID from your data โ€” like a database ID or a unique identifier. Avoid using the array index as a key, especially if the list can be reordered, filtered, or have items added or removed. Indexes change when items move, and that causes bugs.

When you're rendering a list of components, each component gets its own key. This helps React optimize rendering and keep your UI fast. It's not just best practice โ€” it's essential for your app to work correctly.

function TodoItem({ todo }) {
  return <li>{todo.text}</li>;
}

function TodoList() {
  const todos = [
    { id: 1, text: "Learn React" },
    { id: 2, text: "Build a project" },
    { id: 3, text: "Deploy to production" },
  ];

  return (
    <ul>
      {todos.map((todo) => (
        <TodoItem key={todo.id} todo={todo} />
      ))}
    </ul>
  );
}
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What is the purpose of keys in React lists?