React

Lesson 02

Stable keys in lists

Use stable item identities as keys so React can preserve the right state.

Good Code

CommentList.tsx
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>
  ));
}

Bad Code

CommentList.tsx
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>
  ));
}

Review Notes

What to review

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.

Bad Code

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.

Takeaways

  • Prefer durable IDs for list keys instead of array positions.