Home / Learn React / Lists and Keys
Lists and Keys
To show many items, use the array method .map() to turn data into JSX. Give every item a stable key so React can track it.
Theory in plain words
What it is
Rendering a list means turning an array of data into an array of JSX elements. React displays an array of elements one after another.
Why we use it
Most real data is a list: products, messages, users, tasks. You never write each row by hand. You write one row component and map your data over it.
How it works
The key is a label that identifies each item between renders. When the list changes, React uses keys to know which item moved, was added or was removed, so it keeps the right DOM node and state for each one.
Where it is used
- Product grids and tables
- Menus and navigation
- Chat messages and comments
- To do lists and search results
map() turns data into JSX
Filter and sort before you map
toSorted returns a new array. sort changes the original, which you must avoid with state.
Key rules
- A key must be unique among siblings (not across the whole app).
- A key must be stable: do not make it with
Math.random()during render. - Keys are not passed as a prop. If the child needs the id, pass it as another prop.
- Put the key on the outermost element returned by
map, or on the Fragment:<Fragment key={id}>.
See why index keys break
In the index version the typed text stays at position 0 but the label moves. With ids the text follows its row.
Quick quiz
1. What is a key for?
Keys let React match old and new items.
2. Which is the best key for a list of database rows?
A stable unique id from the data is best.
3. What problem can an index key cause?
When items move, the same index points to a different item.
Common questions
What is a key for?
Letting React identify each item between renders. Keys let React match old and new items.
Which is the best key for a list of database rows?
The row id. A stable unique id from the data is best.
What problem can an index key cause?
State sticking to the wrong row after reorder or delete. When items move, the same index points to a different item.