Rendering Lists with .map()
In React, you don't write loops in your JSX. To render a list of items, you take an array of data and transform it into an array of React elements using the standard JavaScript .map() array method.
Let's say you have an array of todo items:
JavaScript
const todos = [
  { id: 1, text: 'Learn React' },
  { id: 2, text: 'Build a project' },
  { id: 3, text: 'Deploy the project' },
];
You can render this as a list in your component like this:
JavaScript
function TodoList() {
  const todos = [
    { id: 'a', text: 'Learn React' },
    { id: 'b', text: 'Build a project' },
    { id: 'c', text: 'Deploy the project' },
  ];
  return (
    <ul>
      {/* Use .map() inside curly braces to create an array of <li> elements */}
      {todos.map(todo => (
        <li key={todo.id}>
          {todo.text}
        </li>
      ))}
    </ul>
  );
}
The expression inside the curly braces evaluates to an array of <li> elements, which React then renders into the DOM.
The Importance of key
Notice the key={todo.id} prop on the <li> element. This is critical. When you render a list, you must provide a key prop to each item in the array.
What is a key? A key is a special string attribute you need to include when creating lists of elements. Keys give the elements a stable identity.
Why are keys important? Keys help React identify which items have changed, are added, or are removed. Without keys, React has to guess. Imagine re-ordering a list. Without keys, React might think you've changed the content of every single item in the list, forcing it to re-render all of them.
With stable keys, React knows that the item with key='b' has just moved, and it can efficiently move the corresponding DOM element without recreating it.
Rules for Keys:
- Keys must be unique among siblings in the list. They don't need to be globally unique.
- Keys should be stable and predictable. Don't use something random like Math.random(). The best key is usually a unique ID from your data (like todo.id).
- As a last resort, you can use the array index as a key, but this is not recommended if the list can ever be re-ordered, added to, or filtered. Using the index can lead to subtle bugs and performance issues.
A Glimpse into Reconciliation
The process React uses to update the UI is called reconciliation. When a component's state or props change, React creates a new "virtual DOM" tree describing the new UI. It then compares this new tree with the previous one.
The key prop is the primary hint React uses during this comparison (or "diffing") process. When React sees children with the same key in both the old and new trees, it will match them up and only apply the necessary changes, making the update process incredibly efficient.