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.

In shortLoop with .map() and give each element a unique, stable key such as an id from your data.

Theory in plain words

Good key vs bad keykey={item.id}stable id from datareorder keeps statecorrect updateskey={index}position changesstate sticks to wrong rowuse only for fixed lists
Good key vs bad key

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

Render an arrayTry it Yourself

Filter and sort before you map

Filter and sortTry it Yourself

toSorted returns a new array. sort changes the original, which you must avoid with state.

Key rules

See why index keys break

Type in a row, then remove the first oneTry it Yourself

In the index version the typed text stays at position 0 but the label moves. With ids the text follows its row.

Careful:Without a key React shows a warning in the console and falls back to index. Never ignore it.

Quick quiz

1. What is a key for?

2. Which is the best key for a list of database rows?

3. What problem can an index key cause?

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.