AI Hints
Home›React Tutorial›Lists and Conditions
React · Lesson 14 of 120

Keys

Why React needs them.

⏱ 2 min read▶ Video at 10:06🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Each item in a list needs a key, a value that's unique and stays the same. When the list changes, keys let React match old items to new ones, instead of rebuilding everything.

  • A key per item
  • Unique and stable
  • React matches items

Choosing keys

The best key is an ID from your data. A unique name can work too. Avoid the array index if items can be added, removed, or sorted. And never use random numbers, which change on every render.

KeyGood?
Database idbest
Unique namefine
Array indexonly if the list never changes
Math.random()never

Without keys

If you forget keys, React warns you in the console. Worse, typed text or checkboxes can end up on the wrong item, after the list changes.

keyvalue
Missing keysconsole warning
Bad keysstate on wrong item
Fixstable ids
Whereon the outer element

Summary

Give every list item a unique, stable key, ideally an ID. Next, conditional rendering.

Key takeaways
  • key={bike.id}
  • Unique
  • Stable
Next up: Conditional Rendering — if, &&, ternary