← Back to React, page 1

react-0006 · Easy fresher

What are keys in React lists, and why do they matter?

A key is a special prop that gives each element in a list a stable identity. React uses it during reconciliation to match old and new items, so it can reorder, add and remove items without destroying and rebuilding the wrong ones. Keys should be unique among siblings and stable across renders. A database id is ideal. An array index is risky when the list can change order.

Full answer

When a list re-renders, React compares the new list of elements with the previous one. Without a clue about which item is which, it can only compare by position. A key is that clue.

With keys, React can see that the item with key 7 moved from the third place to the first. It moves the existing DOM node and keeps the component's state. Without keys, or with index keys, position decides identity, so the third item is reused for whatever data now sits in position three.

This matters most when list items hold state or DOM state: a text input being typed in, a checkbox, focus, an animation, or a component with useState. With index keys, removing the first item makes the second row inherit the first row's typed text. The data moves, but the row state stays in place.

A good key is unique among siblings, stable (the same item always gets the same key) and not random. Use an id from your data. Do not use Math.random() or crypto.randomUUID() in render, since every render creates a new key and React throws the old row away. If items have no id, create one when the data is created, not when it is rendered.

An index key is fine only when the list is static: it never reorders, never gets inserts or deletes in the middle, and its rows hold no state.

Keys are not passed as props. A component cannot read props.key. If the child needs the id, pass it as a separate prop. Keys also work outside lists: changing the key of a component forces React to reset its state, which is a clean way to restart a form.

This is the problem pattern, shown on purpose so it is easy to recognise:

jsx
export default function Rows({ items }) {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item.name}</li> // index key breaks when items reorder
      ))}
    </ul>
  );
}
jsx
import { useState } from 'react';

function Row({ student }) {
  const [note, setNote] = useState('');
  return (
    <li>
      {student.name}: <input value={note} onChange={(e) => setNote(e.target.value)} />
      <span> note={note}</span>
    </li>
  );
}

export default function App() {
  const [students, setStudents] = useState([
    { id: 'a1', name: 'Asha' },
    { id: 'b2', name: 'Ravi' },
    { id: 'c3', name: 'Meera' },
  ]);

  return (
    <>
      <button onClick={() => setStudents((list) => list.slice(1))}>Remove first</button>
      <ul>
        {students.map((s) => (
          <Row key={s.id} student={s} />
        ))}
      </ul>
    </>
  );
}

Each row keeps its own typed note. The check typed a different note in each row and then removed the first student. With key={s.id} the remaining rows keep their own notes. Result: <button>Remove first</button><ul><li>Ravi: <input value="second-note"><span> note=second-note</span></li><li>Meera: <input value="third-note"><span> note=third-note</span></li></ul>

Key points

  • A key tells React which list item is which between renders.
  • Keys must be unique among siblings and stable. Database ids are ideal.
  • Index keys cause state to attach to the wrong row when the list reorders or shrinks.
  • Never generate keys during render with random values.
  • Changing a component's key resets its state, which is useful on purpose.

Common mistakes

  • Using the array index as a key on a list that can be sorted, filtered or edited.
  • Generating random keys in render, which remounts every row on every render.
  • Putting the key on an element inside the component instead of on the element returned by map.
  • Expecting to read props.key inside the child.
  • Using non-unique keys such as a name or a category.

Follow-ups

  • What happens in the DOM when two siblings share the same key?
  • How can changing a key be used to reset a component's state?
  • Is it ever acceptable to use the index as a key?

Tips

  • Use a concrete failure story: removing the first row of a list with inputs. It shows you understand the real bug.
  • Say "stable and unique among siblings". Many candidates forget that keys only need to be unique inside one list.
  • Mention that keys are not available as props.