Lesson 3 of 11 · 12 min · Components
Lists, keys and conditional rendering
What you will learn
- Render lists of data with
map - What the
keyprop is for and how to choose keys - Filter and sort lists before rendering
- Conditional rendering with
if,? :,&&and early returns - Render empty, loading and error states
In simple words
Most screens show lists of things: orders, courses, messages. In React you do not write one line of markup per item; you keep the data in an array and turn each item into a piece of the screen with map. When the list changes, React needs a way to tell which item is which, so you give each one a stable name called a key. And because real screens also need to hide things, show "no results" messages and spinners, you will also learn the ways to decide what to show.
Words to know
- map: the array method that turns each item into something new, here a piece of interface.
- key: a unique, stable identifier React uses to tell list items apart between renders.
- Conditional rendering: showing different JSX depending on a condition.
- Falsy value:
false,0,"",null,undefinedorNaN, treated as false in a condition.
Rendering a list
type Course = { id: number; title: string; lessons: number };
const courses: Course[] = [
{ id: 1, title: "SQL for analysts", lessons: 14 },
{ id: 2, title: "Spring Boot", lessons: 12 },
{ id: 3, title: "React", lessons: 11 },
];
function CourseList() {
return (
<ul>
{courses.map((course) => (
<li key={course.id}>
{course.title} ({course.lessons} lessons)
</li>
))}
</ul>
);
}
courses.map(...) returns an array of JSX elements, and React renders arrays. Each item needs a key. Without it, React warns: "Each child in a list should have a unique key prop."
For a component per item:
{courses.map((course) => (
<CourseCard key={course.id} title={course.title} lessons={course.lessons} />
))}
Note: put the key on the outermost element returned by map (the CourseCard, or the first <li>), not inside the child component. And key is not passed as a prop: the child cannot read it.
Keys
React uses keys to match items between renders: which element is new, which was removed, which only moved. A good key keeps each item's identity (and its state, such as typed text in an input or a playing video) attached to the right data.
Rules:
- Unique among siblings (not globally).
- Stable: the same item always has the same key across renders.
- Not random:
key={Math.random()}creates a new key every render, so React destroys and recreates every item every time, losing state and hurting performance. - Prefer an id from your data (a database id, a slug).
What about the array index?
{items.map((item, index) => <li key={index}>...</li>)} // only OK for static lists
Using the index is acceptable only when the list is static: never reordered, filtered, inserted into or removed from. Otherwise, the index shifts, and React attaches the wrong state to the wrong item (an input's text jumps to a different row). If your data has no id, generate one when the data is created (crypto.randomUUID()), not in the render.
A fragment with a key for several elements per item: <Fragment key={course.id}>...</Fragment> (import Fragment from react; the short <> form cannot take a key).
Transforming data before rendering
Do the work before return, using normal array methods. Do not mutate the original array (sort mutates; use toSorted or copy first):
function CourseList({ courses, query, sortBy }: Props) {
const visible = courses
.filter((c) => c.title.toLowerCase().includes(query.toLowerCase()))
.toSorted((a, b) => (sortBy === "lessons" ? b.lessons - a.lessons : a.title.localeCompare(b.title)));
return (
<ul>
{visible.map((c) => <li key={c.id}>{c.title}</li>)}
</ul>
);
}
Derived data (the filtered list) is computed during render, not stored in state (the state lesson explains why). For very expensive computations on large lists, memoise with useMemo, or, with the React Compiler, often not at all. For long lists (thousands of rows), use virtualisation (TanStack Virtual, react-window) so only visible rows exist in the DOM.
Nested lists work the same way, each level with its own keys:
{modules.map((m) => (
<section key={m.id}>
<h3>{m.title}</h3>
<ul>{m.lessons.map((l) => <li key={l.id}>{l.title}</li>)}</ul>
</section>
))}
Conditional rendering
JSX is JavaScript, so you use JavaScript to decide. The common forms:
An if before the return, best for early exits:
function Profile({ user }: { user: User | null }) {
if (!user) return <p>Please sign in.</p>; // early return
return <h1>Welcome, {user.name}</h1>;
}
A ternary for either-or inside JSX:
<p>{isPaid ? "Paid" : "Pending"}</p>
{isLoggedIn ? <Dashboard /> : <LoginForm />}
&& for "show this or nothing":
{unread > 0 && <span className="badge">{unread}</span>}
Beware the 0 trap: {count && <Badge />} renders the number 0 on the screen when count is 0, because 0 is falsy but is still renderable. Make the condition a boolean: {count > 0 && <Badge />} or {Boolean(count) && ...}.
Returning null renders nothing: if (!visible) return null;.
Variables for complex cases:
let content;
if (status === "loading") content = <Spinner />;
else if (status === "error") content = <ErrorMessage />;
else content = <OrderTable orders={orders} />;
return <section>{content}</section>;
Avoid nested ternaries beyond one level; extract a small component or a lookup instead. For many states, a lookup object keeps it readable:
const badge = { paid: <Paid />, pending: <Pending />, refunded: <Refunded /> }[order.status];
false, null, undefined and true render nothing; numbers and strings render as text; objects are not valid to render ({order} throws "Objects are not valid as a React child").
Empty, loading and error states
Every list that comes from data has more than one state; show each deliberately:
function Orders({ status, orders, error, onRetry }: OrdersProps) {
if (status === "loading") return <p role="status">Loading orders...</p>;
if (status === "error") {
return (
<div role="alert">
<p>We could not load your orders.</p>
<button type="button" onClick={onRetry}>Try again</button>
</div>
);
}
if (orders.length === 0) return <p>No orders yet. <a href="/learn">Start learning</a></p>;
return (
<ul>
{orders.map((o) => <li key={o.id}>#{o.id}: {o.amount}</li>)}
</ul>
);
}
Good habits: a helpful empty state with a next action, skeleton placeholders instead of spinners for known layouts, aria-live/role="status" for announcements, keep old data visible while refreshing, and a retry button on errors.
Showing and hiding versus mounting
Conditional rendering with && or a ternary removes the component from the tree: its state is lost when it disappears. If you want to keep the state (a half-filled form in a hidden tab), either keep the component mounted and hide it with CSS (hidden attribute or a class) or lift the state up. React 19.2 adds an <Activity> component that hides a part of the UI while preserving its state.
Also: the same component at the same position keeps its state between renders; a different component type or a different key resets it. You can use that on purpose: <ProfileForm key={user.id} user={user} /> starts a fresh form when the user changes.
Common bugs
| Symptom | Cause |
|---|---|
| "Each child in a list should have a unique key" warning | missing key |
| Inputs in a list keep the wrong text after sorting or deleting | index used as the key on a dynamic list |
| Everything in the list resets on every render | a random or changing key |
A stray 0 appears on screen |
{number && <X />} |
| "Objects are not valid as a React child" | rendering an object or a Date directly: format it first |
| The list does not update | the array was mutated (push, sort) instead of replaced |
| Duplicate-key warnings | non-unique ids; check your data |
| State lost when toggling | conditional rendering unmounted the component |
Common mistakes
- Missing, random or index keys on dynamic lists.
{count && <Badge />}with a number.- Mutating the array you map over.
- Using a
keyon the inner element instead of the outer one returned bymap. - Nested ternaries that nobody can read.
- No empty, loading or error state.
- Storing a filtered list in state instead of computing it.
Try it yourself
- Render a list of courses with
mapand ids as keys, and then see the warning when you removekey. - Add a search box that filters the list (computing the filtered list in render, not state).
- Reproduce the index-as-key bug: a list with an
<input>in each row and a "reverse" button, then fix it with ids. - Show the
0trap with a badge, and fix it. - Write a component with loading, error, empty and success states.
Check yourself
What is the key prop for?
It gives each list item a stable identity so React can match items between renders and update, move or remove the right ones while preserving their state.
Why is key={Math.random()} bad?
The key changes on every render, so React treats every item as new, discarding and recreating them all, losing state and hurting performance.
When is it acceptable to use the array index as a key?
When the list is static (never reordered, filtered or changed in the middle) and has no stable id.
Why does {count && <Badge />} sometimes show 0?
0 is falsy so && returns it, and React renders the number zero; use count > 0 && instead.
Interview questions
Why do React lists need keys?
Keys let React's reconciliation identify which items changed, were added, removed or moved, so it can reuse the right DOM nodes and component state; without stable keys it may reorder incorrectly or reset state.
What are the ways to render conditionally in React?
if statements and early returns, ternary operators, the && operator, returning null, assigning JSX to variables, and lookup objects or small components for many cases.
How do you preserve a component's state when it is hidden?
Keep it mounted and hide it with CSS (or the Activity component), or lift its state to a parent that stays mounted; conditional rendering unmounts it and loses its state.
Summary
- Render lists with
mapand a stable, uniquekeyfrom your data; avoid random keys and index keys on dynamic lists. - Filter and sort derived data during render without mutating the source.
- Use early returns, ternaries and
&&(careful with0) for conditions; model loading, error, empty and success states. - Remember that unmounting loses state; a changed
keyresets it.
Going deeper
- React: Rendering lists:
map,filterand keys. - React: Conditional rendering: the patterns in detail.
- React: Preserving and resetting state: how position and keys decide identity.
- React: Activity: hiding UI while keeping its state.
See how much of this you can explain
A free mock interview asks you new questions on React: components, state, routing and testing for Frontend Developer and scores every answer, with what to fix.