Rendering Lists & The Importance of Keys in React
Transforming arrays into JSX with map(), choosing stable unique keys, and why array index keys cause state corruption bugs.
Rendering Lists & The Importance of Keys in React
To render multiple similar components from a collection of data, use JavaScript's built-in .map() method to transform an array of data into an array of JSX elements.
1. Basic List Rendering
interface Article {
id: string;
title: string;
}
export function ArticleList({ articles }: { articles: Article[] }) {
return (
<ul>
{articles.map((article) => (
<li key={article.id}>
<a href={`/docs/${article.id}`}>{article.title}</a>
</li>
))}
</ul>
);
}2. Why React Demands key Props
React uses the key prop to uniquely identify each item in a list across re-renders. Keys allow React's reconciliation algorithm to determine which items were added, removed, reordered, or edited, rather than destroying and re-mounting every DOM node from scratch.
3. The Array Index Key Anti-Pattern
Rules for Keys:
- Keys must be unique among siblings: Items in the same array must have distinct keys.
- Keys must be stable: Do NOT generate keys on the fly like
key={Math.random()}. Use database IDs (item.id) or stable unique slugs.
Related Topics
Conditional Rendering in React
Techniques for conditional UI rendering: ternary operators, logical AND (&&), if/else return statements, and preventing the zero rendering bug.
React Forms & Controlled Components
Managing form state in React: controlled vs uncontrolled inputs, form submission handling, multi-input state patterns, and React 19 Actions.