Lists and Keys

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

Lists and Keys

In React, you will often want to render multiple similar components from a collection of data. You can do this by using standard JavaScript array methods, particularly .map(), to iterate over the data and return an array of JSX elements.

Rendering a List

To render a list, you map over an array of data and return a JSX element for each item.

const people = ['Creola Katherine Johnson', 'Mario José Molina-Pasquel Henríquez', 'Mohammad Abdus Salam'];

function PeopleList() {
  const listItems = people.map((person, index) => 
    <li key={index}>{person}</li>
  );
  
  return <ul>{listItems}</ul>;
}

The Importance of key

When you run the code above without a key prop, React will give you a warning in the console:
Warning: Each child in a list should have a unique "key" prop.

Keys help React identify which items have changed, are added, or are removed. This is crucial for the reconciliation algorithm (React’s virtual DOM diffing engine). Without keys, React doesn’t know which specific item was changed if you reorder, add, or delete items, leading to severe performance issues and bugs with state (like input focus jumping around).

Rules of Keys

  1. Keys must be unique among siblings: A key only needs to be unique within the array it belongs to. It does not need to be globally unique.
  2. Keys must not change: Do not generate keys on the fly (e.g., using Math.random()). Keys must remain consistent across renders.

Where to get your keys

Your data will usually have unique identifiers:

  • Database IDs: If your data comes from a database, use the database IDs (e.g., user.id).
  • Locally Generated IDs: If your data is generated locally, use an ID generation library like uuid or crypto.randomUUID() when creating the item.
const listItems = users.map(user => 
  // 'user.id' is a stable, unique identifier from the database
  <li key={user.id}>
    {user.name}
  </li>
);

Using Index as a Key (The Anti-Pattern)

React defaults to using the array index as the key if you don’t provide one. You should avoid using the index as a key if the order of items may change (e.g., sorting, filtering, inserting, deleting).

Using the index as a key when the list order changes can cause React to incorrectly associate state with the wrong component.

Only use the array index as a key if:

  1. The list and items are static (they are never computed or changed).
  2. The items in the list have no ids.
  3. The list is never reordered or filtered.

Interview Questions

Q: Why are key props necessary when rendering lists in React?
A: Keys help React’s reconciliation algorithm uniquely identify which items have changed, been added, or been removed. Without stable keys, React has to mutate the DOM blindly, which destroys performance and causes bugs with component state (like inputs losing focus or carrying over text).

Q: Why is using the array index as a key considered an anti-pattern?
A: If the list is completely static, the index is fine. But if the list can be reordered, filtered, or items can be added/deleted at the top, the indexes shift. React will incorrectly think that the content of the item changed rather than its position, leading to massive unnecessary re-renders and misaligned internal state.