React Best Practices

Chapter 1 · Practice 3 of 5

Give list items stable, unique keys from your data

From Components and purity

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 choiceWhen it is safe
An id from the data (database id, slug)Always: the recommended default
The array indexOnly for static lists that never reorder, filter or prepend
Math.random() or crypto.randomUUID() in renderNever: 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.id or another value that never changes for that item

Avoid

  • key={Math.random()} or key={crypto.randomUUID()} inside render
  • Index keys on lists that can be sorted or filtered