Lists, Keys and When React Re-renders
Render lists with stable keys, learn how React matches elements between renders, and predict exactly when a component re-renders — and when its state survives or resets.
Contentsand lesson path
On this page
- Why it matters
- Rendering lists — and the key
- When React re-renders
- Preserved or reset: state and identity
- Check your understanding
- Apply it
- Review prompt
Lessons of React Components & State
- From Mockup to Component Tree Concept · 20 min
- JSX, Typed Props and Composition Worked example · 25 min
- State, Events and Immutable Updates Worked example · 25 min
- Lists, Keys and When React Re-renders Concept · 20 min
- Lab: A Filterable, Sortable Product Table Lab · 30 min
- Check: Predict the Component Behavior Knowledge check · 6 questions
What you will learn
- Render lists with stable keys and conditional content, and predict when a component re-renders and when its state is preserved or reset.
Prerequisites: JavaScript Foundations
01. Why it matters
Most interfaces are lists in disguise: product tables, notification feeds, filter rows. And most "React is slow" or "my edit landed in the wrong row" reports trace back to two mechanisms this lesson makes explicit: how React matches old output to new when a list changes, and when a component is asked to render again. Get both right and you can predict what the screen will do after any interaction — the difference between debugging React and fighting it.
Every claim below is demonstrated by a test you could run yourself, in the same Testing Library style as the last lesson.
02. Rendering lists — and the key
A list is rendered by mapping data to elements. Each element needs a key prop: a short string (or number) that is stable for that piece of data and unique among its siblings. The key is not for you — React uses it as an identity card when the list changes. Here is a deliberately small demonstration: a list of fruit, each row containing its own counter button, keyed either by the row's index or by the fruit's name.
import { useState } from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, it } from 'vitest';
function Counter() {
const [n, setN] = useState(0);
return (
<button type="button" onClick={() => setN(n + 1)}>
{n}
</button>
);
}
function FruitList({ items, byIndex }: { items: string[]; byIndex?: boolean }) {
return (
<ul>
{items.map((name, index) => (
<li key={byIndex ? index : name}>
{name}: <Counter />
</li>
))}
</ul>
);
}it('with index keys, state stays at the position', async () => {
const user = userEvent.setup();
const { rerender } = render(<FruitList items={['Apple', 'Pear']} byIndex />);
const [appleButton, pearButton] = screen.getAllByRole('button');
await user.click(appleButton);
await user.click(pearButton);
await user.click(pearButton);
rerender(<FruitList items={['Pear', 'Apple']} byIndex />);
const [first, second] = screen.getAllByRole('button');
expect(first).toHaveTextContent('1');
expect(second).toHaveTextContent('2');
});
it('with stable keys, state follows the item', async () => {
const user = userEvent.setup();
const { rerender } = render(<FruitList items={['Apple', 'Pear']} />);
const [appleButton, pearButton] = screen.getAllByRole('button');
await user.click(appleButton);
await user.click(pearButton);
await user.click(pearButton);
rerender(<FruitList items={['Pear', 'Apple']} />);
const [first, second] = screen.getAllByRole('button');
expect(first).toHaveTextContent('2');
expect(second).toHaveTextContent('1');
}); ✓ src/keys.test.tsx (2 tests)
Test Files 1 passed (1)
Tests 2 passed (2)Apple's counter was clicked once and Pear's twice. After the rows swap, the two tests disagree about where those numbers live. With index keys, the counter showing 1 stays in row 0 even though row 0 now holds Pear — React matched by position, so the state stayed behind and the fruit moved away from it. With keys taken from the data, the state travels with its item. Both runs are consistent with React's rule; only one matches what a user means.
The practical rules follow: derive keys from the data (product.sku, item.id) rather than from the loop index, and never from Math.random() — a new key every render tells React the row is a different component, so its state is thrown away each time. Index keys are tolerable only when the list never reorders, filters or removes, which is a promise few lists keep. The filterable list lab from the DOM skill hits the same requirement in plain JavaScript with dataset.id — keys are React's built-in version of that idea.
03. When React re-renders
A render is React calling your component function to get new output. It is not the same as the DOM changing: React compares the new output with the old one and touches the document only where something actually differs. A component renders again when its own state changes — and, by default, whenever its parent renders, whether or not any prop changed. That second rule surprises everyone, so here is a component that counts its own renders.
import { useState } from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, it } from 'vitest';
let renders = 0;
function Child({ label }: { label: string }) {
renders += 1;
return <p>{label}</p>;
}
function Parent() {
const [n, setN] = useState(0);
renders += 1;
return (
<div>
<button type="button" onClick={() => setN(n + 1)}>
Count: {n}
</button>
<Child label="Props never change" />
</div>
);
}
it('re-renders children when the parent re-renders', async () => {
const user = userEvent.setup();
render(<Parent />);
console.log('after mount: renders =', renders);
await user.click(screen.getByRole('button', { name: 'Count: 0' }));
console.log('after 1 click: renders =', renders);
await user.click(screen.getByRole('button', { name: 'Count: 1' }));
console.log('after 2 clicks: renders =', renders);
expect(renders).toBe(6);
});stdout | src/rerender.test.tsx > re-renders children when the parent re-renders
after mount: renders = 2
stdout | src/rerender.test.tsx > re-renders children when the parent re-renders
after 1 click: renders = 4
stdout | src/rerender.test.tsx > re-renders children when the parent re-renders
after 2 clicks: renders = 6
✓ src/rerender.test.tsx (1 test)
Test Files 1 passed (1)
Tests 1 passed (1)Two components, one counter that Child never reads — and every click renders both. The count climbs by two per click because a parent render asks every child to render too; React then discards the unchanged output. This is the design that keeps React correct by default: no component can miss an update because someone forgot to notify it. Projects that turn on the React Compiler (stable since October 2025, and opt-in through a build plugin) get components and JSX memoised automatically, so unchanged child renders are skipped; without the compiler, memo can opt an expensive subtree out by hand. (These tests use the packages, vitest.config.ts and setup file from step 4 of the state lesson; the setup file's cleanup matters here, because each file renders twice. Counting renders with a module variable such as renders is for illustration only.)
One more wrinkle you will meet immediately in development: StrictMode deliberately calls every component function twice per render to surface code that depends on render counts or mutates values during render. The tests above do not enable it; your dev server does — if a similar counter shows double in npm run dev, that is StrictMode working, not a bug.
04. Preserved or reset: state and identity
Keys also answer the question "where does my state go?". React keeps a component's state as long as the same component type stays at the same position in the tree. Change the position, render a different component type there, or change the key — and React unmounts the old component, throwing its state away, then mounts a fresh one. A Scoreboard shows both behaviours in one component.
import { useState } from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, it } from 'vitest';
function Tally({ seed }: { seed: number }) {
const [n, setN] = useState(seed);
return (
<button type="button" onClick={() => setN(n + 1)}>
{n}
</button>
);
}
function Scoreboard({ keyByPlayer }: { keyByPlayer: boolean }) {
const [player, setPlayer] = useState<'one' | 'two'>('one');
return (
<div>
<p>Player: {player}</p>
<Tally key={keyByPlayer ? player : undefined} seed={player === 'one' ? 0 : 100} />
<button type="button" onClick={() => setPlayer('two')}>
Switch player
</button>
</div>
);
}it('state survives at the same position without a key', async () => {
const user = userEvent.setup();
render(<Scoreboard keyByPlayer={false} />);
await user.click(screen.getByRole('button', { name: '0' }));
await user.click(screen.getByRole('button', { name: '1' }));
await user.click(screen.getByRole('button', { name: '2' }));
await user.click(screen.getByRole('button', { name: 'Switch player' }));
expect(screen.getByRole('button', { name: '3' })).toBeVisible();
await user.click(screen.getByRole('button', { name: '3' }));
expect(screen.getByRole('button', { name: '4' })).toBeVisible();
});
it('a changed key resets the state at that position', async () => {
const user = userEvent.setup();
render(<Scoreboard keyByPlayer />);
await user.click(screen.getByRole('button', { name: '0' }));
await user.click(screen.getByRole('button', { name: '1' }));
await user.click(screen.getByRole('button', { name: '2' }));
await user.click(screen.getByRole('button', { name: 'Switch player' }));
expect(screen.getByRole('button', { name: '100' })).toBeVisible();
await user.click(screen.getByRole('button', { name: '100' }));
expect(screen.getByRole('button', { name: '101' })).toBeVisible();
}); ✓ src/reset.test.tsx (2 tests)
Test Files 1 passed (1)
Tests 2 passed (2)Without a key, the tally keeps counting from 3 after the player switches — same component type, same position, so the state survives and the new seed is ignored (it is only read on mount). With key={player}, switching players mounts a fresh Tally starting from 100. Neither behaviour is a bug; you choose which one the interface needs by choosing the key. A resetting key is the idiomatic fix for "my form kept the previous user's draft" — and a forgotten key is why "my counter reset itself".
The same position-and-type logic drives conditional rendering. Swapping <ul>{items.map(…)}</ul> for <p>Your cart is empty.</p> based on items.length === 0 unmounts one and mounts the other, fresh. Conditions written with && must produce a boolean on the left: hasItems && <Badge /> renders nothing when false, but an expression whose falsy value is the number 0 prints that 0 as text, so prefer count > 0 && … or a ternary when the left side is a number. Filtered-out lists and their counts — like the lab's status line — are exactly where this shows up.
05. Check your understanding
06. Apply it
Open the shopping list you built in the last lesson, install React DevTools in your browser, and watch the Components panel while you tick boxes and add items: the components that flash are the ones that re-rendered. Then prove your predictions — before each interaction, say which components will render and which state will survive, and check. Swap two list items and watch whether any row's local state moves; if it does, your keys are not stable. Record a screenshot of the flash on the parent and its children, which is part of the evidence the practice brief for this skill asks for.
07. Review prompt
Without looking back: state the two rules a good key must satisfy, the two events that make a component render again, and the three things that make React throw a component's state away. Then explain to an imaginary colleague why the list of a search box should be keyed by result id, not by position.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.