Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 132 ยท Components and Props

Rendering Lists and Keys

Render lists in React with map(), choose stable keys, see what goes wrong with index keys, filter and sort derived lists, handle empty states and nest lists.

Almost every app shows lists: messages, products, search results, comments, table rows. In React you do not write a loop in the markup. Instead you take an array of data and turn it into an array of elements with the ordinary JavaScript method map(). React renders arrays of elements natively.

There is one extra rule, and it is the part beginners skip and professionals respect: every item in a list needs a key. This lesson shows how to render a list, what a key is for, how to pick a good one, a runnable demonstration of what goes wrong with the wrong key, and how to filter, sort and nest lists. It builds on Conditional Rendering; the deeper mechanics of keys are in Reconciliation and Keys in Depth.

Rendering an array with map()

array.map(fn) returns a new array by calling fn on each item. If fn returns JSX, you get an array of elements, and you can drop it straight into your JSX:

From an array of data to a list

Read it as three steps: the data is an array of objects; map converts each object to an <li>; the result is placed in the <ul>. Note the arrow function uses parentheses around the JSX, so it returns it. If you used curly braces for the arrow body you would need an explicit return, and forgetting it renders nothing.

To pull the item into its own component, pass the data as props and keep the key on the element created inside the map, not inside the component:

JSX
{fruits.map((fruit) => (
  <FruitItem key={fruit.id} name={fruit.name} color={fruit.color} />
))}

What a key is

A key is a string or number you put on each element of an array so React can tell the elements apart between renders. When the list changes, React compares the old and the new arrays and uses keys to answer: "which item is this one now?" With a good key React moves, adds or removes exactly the right items. Without keys it can only match by position, which gives wrong results as soon as the list is reordered, filtered, or edited.

Important details:

  • Keys only need to be unique among siblings in the same array, not across the app.
  • key is not a prop: your component never receives it. If you need the value, pass it again under another name (id={item.id}).
  • Keys must be stable: the same item must have the same key on every render. A key that changes makes React destroy and recreate the item.
  • Forgetting keys makes React log this console error in development, which you will also see in our editor if you delete a key from an example: Each child in a list should have a unique "key" prop. followed by a link to the explanation.

Where do keys come from?

Use data that identifies the item: a database id, a slug, a product SKU. If you create items in the browser (an "add todo" form), generate an id once, when the item is created, and store it with the item:

JSX
let nextId = 1;
function addTodo(text) {
  return { id: nextId++, text, done: false };
}

crypto.randomUUID() also works. What you must not do is generate the key during rendering (key={Math.random()}): that creates a new key every render, so every item is thrown away and rebuilt every time, losing focus, scroll position and state.

The index-as-key trap

The array index is the key people reach for when they have no id. key={index} silences the warning, so it looks fine, and it is fine for lists that are static: never reordered, never filtered, never inserted into at the front or the middle. For everything else it is a bug waiting to happen.

Here is a list where each row has a bit of its own state: an uncontrolled text input that remembers what you typed. Both lists show the same three names and have a "Move first to end" button.

Index keys versus id keys

Type "hello" in the first input of each list (next to Ada), then press Move first to end in each section.

  • In the index list the names rotate (Bo, Cy, Ada), but the text "hello" stays in the first row, now next to Bo. React saw "row 0, row 1, row 2" before and after, so it reused the same three Row instances and just changed their name prop. The input's text belongs to the instance, not to Ada, so it stayed behind.
  • In the id list the text follows Ada to the bottom, because React matched rows by identity and moved the Row instance for Ada.

Bugs from index keys do not only show up as misplaced input text. They also appear as wrong animations, effects that do not re-run, stale useState values, lost focus and unnecessary re-mounting. When in doubt, use an id.

An index key is acceptable when all three are true: the list is never reordered or filtered, items are never inserted or removed except at the end, and the items hold no state. If you cannot promise all three, add an id.

Derived lists: filter and sort

A list on screen is usually a view of your data: filtered by a search box, sorted by a column. Do not store the filtered list in state. Keep the original data, plus the filter value, and compute the visible list during render. That keeps one source of truth (Choosing a State Structure).

Filter and sort a list

Two details. filter already returns a new array, so calling sort on it (which sorts in place) is safe here. Calling books.sort(...) directly would mutate the original array, which is a bug; to sort a prop or a state array, copy first with [...items].sort(...) or use toSorted(...). And the ternary handles the empty state: a good list always says what is happening when it has no rows ("No books match..."), instead of showing an unexplained blank.

Several elements per item: keyed fragments

Sometimes each item produces more than one sibling element, for example a term and its description in a <dl>. A short fragment <>...</> cannot take a key, so import Fragment and write it out:

A keyed Fragment per item

Nested lists

Lists can contain lists. Each level has its own map and its own keys; because keys only need to be unique among siblings, the same key may appear at different levels.

Nested lists

When a nested level has a lot of markup, extract it: <CourseItem key={course.id} course={course} /> containing its own map. Deeply nested map calls inside one JSX tree get hard to read.

Practical rules and performance notes

  • Do not mutate while rendering. Never push to or sort the array you are mapping over if it comes from props or state.
  • Keep map callbacks simple. If it grows beyond a few lines of JSX, extract a component.
  • key goes on the outermost element returned by map. If you wrap items into a component, the key goes on the component tag, not on an element inside.
  • Large lists. Rendering thousands of rows is slow no matter how good your keys are. For that, see Large Lists and Virtualization.
  • Changing a key resets state on purpose. <Profile key={userId} /> gives each user a fresh component; this is a legitimate technique (State with useState).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the purpose of the key prop on list items?

    Keys give list items a stable identity. Your component does not receive key as a prop.
  2. 2. Which is the best key for a list of database records?

    A stable, unique id is ideal. Random keys change every render, indexes break on reorder or insert, and duplicate titles are not unique.
  3. 3. Rows in a list contain inputs with their own typed text. The list is reordered while using key={index}. What happens?

    With index keys React matches by position and reuses the instances, so the instance's own state stays at the same position while props change.
  4. 4. How should you display only the books that match a search box?

    Derive the visible list during render. Duplicated state can drift out of sync, and removing data loses it.
  5. 5. You need two sibling elements (dt and dd) per list item with a key. What do you use?

    The short <> syntax cannot accept attributes, so use the Fragment component to attach a key.

Summary

  • Turn arrays into elements with map(), returning JSX from the callback.
  • Every item needs a key: a stable, unique identity among siblings, usually an id from your data.
  • Create ids when items are created, not during render; never use random keys.
  • Index keys are only safe for static lists; otherwise state and DOM stay with the position instead of the item.
  • Derive filtered and sorted views during render; copy before sorting and always handle the empty case.
  • Use Fragment with a key when an item produces several siblings.

Next: Keeping Components Pure