Chapter 1 · Practice 3 of 5
Give list items stable, unique keys from your data
Why it matters
Keys tell React which item is which between renders. Get them wrong and state and input values jump to the wrong row, and animations glitch.
| Key choice | When it is safe |
|---|---|
| An id from the data (database id, slug) | Always: the recommended default |
| The array index | Only for static lists that never reorder, filter or prepend |
Math.random() or crypto.randomUUID() in render | Never: a new key every render remounts every row |
If your data has no id, generate ids when you create the data, not during render. With index keys on a list that can be sorted or filtered, React matches the wrong items after the order changes.
Do
- Use
item.idor another value that never changes for that item
Avoid
key={Math.random()}orkey={crypto.randomUUID()}inside render- Index keys on lists that can be sorted or filtered