React Lists, Stable Keys, and Conditional UI
Render arrays with map, choose stable keys that survive filtering, and show clear loading, empty, and error states in React interfaces.
Map collection data to React elements and give each row a stable key so its state stays attached to the right record. The examples use filtering and explicit loading, error, and empty branches to make updates clear. You’ll also see when an index key is safe, why random keys fail, and how to distinguish an empty filter from a successful request with no results.
React Lists, Stable Keys, and Conditional UI
Introduction
React screens often show collections. Use map to turn an array into elements, give each item a stable key, and explain loading, empty, and error states.
This guide covers list rendering, identity-safe keys, filtering, and the UI states users need while data changes.
Render an array with map
Map turns each record into an element. Put the key on the outer element returned by the map, using an ID that stays with the record:
interface Task {
id: string;
title: string;
done: boolean;
}
function TaskList({ tasks }: { tasks: Task[] }) {
return (
<ul>
{tasks.map((task) => (
<li key={task.id}>{task.title}</li>
))}
</ul>
);
}
Keep keys stable when filtering
Filtering creates a new array, but records keep their identity. Key the item, not its current position.
const visibleTasks = tasks.filter((task) => !task.done);
return visibleTasks.map((task) => <TaskRow key={task.id} task={task} />);
An index can work for a static list, but filtering, sorting, or insertion shifts positions. React may reuse a row for another task and show the wrong input value. Prefer a stable ID; if needed, assign one when data enters the app.
Try filtering and reordering
This example keeps a draft note inside each row. Type a note, then filter or reverse the sample tasks. The stable key keeps each row’s state with its task:
import { useState } from "react";
interface TaskItem {
id: string;
title: string;
}
function TaskRow({ task }: { task: TaskItem }) {
const [note, setNote] = useState("");
return (
<li>
<span>{task.title}</span>
<label>
Note for {task.title}
<input value={note} onChange={(event) => setNote(event.target.value)} />
</label>
</li>
);
}
function TaskExplorer({ tasks }: { tasks: TaskItem[] }) {
const [query, setQuery] = useState("");
const [reversed, setReversed] = useState(false);
const matchingTasks = tasks.filter((task) =>
task.title.toLowerCase().includes(query.toLowerCase()),
);
const visibleTasks = reversed ? [...matchingTasks].reverse() : matchingTasks;
return (
<>
<label htmlFor="task-filter">Filter tasks</label>
<input
id="task-filter"
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
<button type="button" onClick={() => setReversed((value) => !value)}>
Reverse order
</button>
<p role="status" aria-live="polite">
{visibleTasks.length} {visibleTasks.length === 1 ? "task" : "tasks"}{" "}
shown.
</p>
{tasks.length === 0 ? (
<p>No tasks have been added yet.</p>
) : visibleTasks.length === 0 ? (
<p>No tasks match this filter.</p>
) : (
<ul>
{visibleTasks.map((task) => (
<TaskRow key={task.id} task={task} />
))}
</ul>
)}
</>
);
}
function TaskDemo() {
const tasks = [
{ id: "draft", title: "Draft report" },
{ id: "review", title: "Review report" },
{ id: "publish", title: "Publish report" },
];
return <TaskExplorer tasks={tasks} />;
}
To see the index-key bug, temporarily change key={task.id} to key={index} and add the index parameter to map. Type a note, then reverse the list. React now matches row state by position, so a note can appear beside a different task. Filtering away an earlier row can cause the same mismatch among the rows that remain. Restore the ID key after trying it.
After a successful load, pass an empty array to TaskExplorer to show that there are no tasks. With the sample data, filtering for “meeting” shows the separate no-matches message.
Show the right state
Handle loading, failure, empty, and ready states explicitly instead of showing a blank area.
function TaskResults({
loading,
error,
tasks,
}: {
loading: boolean;
error: string | null;
tasks: Task[];
}) {
if (loading)
return (
<p role="status" aria-live="polite">
Loading tasks…
</p>
);
if (error) return <p role="alert">Could not load tasks: {error}</p>;
if (tasks.length === 0) return <p>No tasks have been added yet.</p>;
return <TaskList tasks={tasks} />;
}
Show loading while waiting, an error after a failed request, and an empty state after a successful request with no tasks. In a filtered view, check the unfiltered collection first: no tasks have been added is different from no tasks matching the current filter. The status role announces progress and result-count changes politely; alert is for an important error that needs attention.
Render flow
flowchart TD
A[Request state] --> B{Loading?}
B -->|Yes| C[Loading message]
B -->|No| D{Error?}
D -->|Yes| E[Error message]
D -->|No| F{Any visible items?}
F -->|No| G[Empty state]
F -->|Yes| H[Mapped rows with stable keys]
Trade-Off Table
| Choice | Works well when | Risk |
|---|---|---|
| Stable record ID | Items can reorder or be filtered | Needs a real, persistent identifier |
| Array index | List is fixed and never reordered | State can attach to the wrong row after changes |
| Conditional branches | Loading, error, and empty states differ | Too many nested branches become hard to scan |
| Shared status component | Several screens use the same state UI | Extra abstraction for a one-off list |
Production Failure Scenarios
With index keys, removing a task can move its checked state to another row. Use task IDs so row state follows the task. A second failure appears when a filtered list is derived from stale data: users remove an item, but it remains visible until refresh. Derive the visible list from the current source array and filter state.
Common Pitfalls / Anti-Patterns
Avoid missing or random keys, mixing up empty results and errors, or showing an error while still loading.
Observability Checklist
- Measure request duration and failure rate.
- Track empty results separately from errors.
- Keep private row data out of logs.
Security and Compliance Notes
API data is untrusted. JSX interpolation escapes text; validate fields before use and sanitize intentionally supported HTML. Keys do not validate data.
When to Use / When NOT to Use
Use map when a collection determines repeated UI, and stable record IDs when rows may reorder or hold state. Do not create a dynamic list for a few fixed controls, or use array positions as keys for sortable or filtered data.
Quick Recap Checklist
- Use
mapto create one element per array item. - Key each sibling with a stable identifier from its data.
- Keep keys attached to records when filtering or sorting.
- Show distinct loading, error, and empty states.
- Validate external data and render untrusted strings as text.
Interview Questions
Keys help React match children with the same items between updates, preserving the right DOM and component state.
Filtering changes positions, so React may reuse a row and move its input or checkbox state to another record.
Empty means the request succeeded with no visible items; error means it failed. Separate messages help users choose what to do.
Keys need to be unique among the rendered siblings in one list.
- They do not need to be globally unique across the app.
- Use stable data identity, such as a record ID.
It changes on every render, so React sees each row as a new item.
- Rows can remount and lose local state.
- Choose or assign a stable ID when data enters the app.
No. Filtering changes positions while the underlying records retain their identity.
- Key by the record ID after filtering.
- This keeps row state attached to the correct record.
An empty result means the completed request returned nothing; a filtered empty view means no current records match the filter.
- Tell the user whether to change a filter or retry a request.
- Do not show either state before loading finishes.
The array may be empty because the request has not returned yet.
- Render the loading state first.
- Show empty only after a successful result contains no visible items.
No. React uses the key for matching siblings and does not expose it as a regular prop.
- Pass an ID separately if the child needs it.
- Keep the key on the element returned by the map operation.
No. Keys help React track items but do not check the fields in each record.
- Validate external data before mapping it.
- Render untrusted strings as text and sanitize supported HTML.
Further Reading
- For request lifecycle patterns behind loading and failure UI, see fetching and typing API data and loading and error states.
- React state with useState explains the immutable updates that keep derived lists in sync.
- Controlled inputs and forms shows how input state follows the value rendered by a component.
- Practice user-visible list behavior with component and interaction testing.
- For callbacks and flexible row content, continue to props, children, and composition.
- React’s guides cover rendering lists and conditional rendering; TypeScript’s reference explains array types.
- WAI’s status message technique explains polite live-region announcements.
Conclusion
Map arrays to elements with stable record keys. Give loading, empty, and failure states distinct messages to avoid confusing interfaces and state bugs.
Category
Tags
Related Posts
Accessible React UI: Semantics, Labels, and Keyboard Use
Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.
Advanced React State: When Local State Stops Fitting
Learn when React state needs a reducer and context, when Redux Toolkit helps, and why server data often belongs in a query cache instead.
Testing React Components and User Interactions
Write behavior-first React tests with accessible roles, realistic user events, and async assertions while avoiding brittle checks of implementation details.