Blog>
Snippets

Virtual DOM - Using Keys for List Items

Illustrate the importance of using keys for list items in Virtual DOM to maintain state and improve performance during re-rendering.
function ListItem({ item }) {
  // Each item gets rendered with a unique key
  return <li key={item.id}>{item.text}</li>;
}
This component represents a list item, which should include a unique 'key' prop when it's rendered. The key helps React identify which items have changed, are added, or are removed, thus it enables efficient update of the user interface.
function NumberList({ numbers }) {
  const listItems = numbers.map((number) =>
    // The key should be unique among the siblings
    // We can use the number itself as key if it's unique
    <ListItem key={number.toString()} item={{ id: number, text: `Item ${number}` }} />
  );
  return <ul>{listItems}</ul>;
}
This function component `NumberList` takes an array of numbers, maps through it to create a new `ListItem` component for each number, and attaches a unique key for each `ListItem`. The key used here is the string representation of the number itself, which is assumed to be unique in this context.