React · Lesson 14 of 120
Keys
Why React needs them.
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.
| Key | Good? |
|---|---|
| Database id | best |
| Unique name | fine |
| Array index | only 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.
| key | value |
|---|---|
| Missing keys | console warning |
| Bad keys | state on wrong item |
| Fix | stable ids |
| Where | on 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