Good Code
The good version uses the comment ID as the key, so React can keep each rendered item attached to the same comment when the list changes.
Lesson 02
Use stable item identities as keys so React can preserve the right state.
type Comment = {
id: string;
authorName: string;
body: string;
};
export function CommentList({ comments }: { comments: Comment[] }) {
// Stable IDs preserve the right item identity across list changes.
return comments.map((comment) => (
<article key={comment.id}>
<h3>{comment.authorName}</h3>
<p>{comment.body}</p>
</article>
));
}type Comment = {
id: string;
authorName: string;
body: string;
};
export function CommentList({ comments }: { comments: Comment[] }) {
// Index keys describe position, not the comment's identity.
return comments.map((comment, index) => (
<article key={index}>
<h3>{comment.authorName}</h3>
<p>{comment.body}</p>
</article>
));
}The good version uses the comment ID as the key, so React can keep each rendered item attached to the same comment when the list changes.
The bad version uses the array index, which only represents a position. Insertions, removals, and sorting can make React reuse the wrong DOM or component state for another comment.