Blog>
Snippets

Debugging Common Mistakes: Incorrect Item Key Usage

Highlight a common mistake made while using TanStack Virtual by providing an incorrect vs. correct way of assigning keys to list items, showcasing the impact on performance and re-rendering.
const IncorrectKeyUsage = () => {
  return virtualItems.map((virtualRow, index) => (
    // Using index as a key, leading to potential issues when the list changes
    <div key={index} style={virtualRow.style}>...</div>
  ));
};
This snippet demonstrates the incorrect way of using the index as a key in a map function. This can lead to performance issues and bugs in React applications, especially in dynamic lists where the order of items can change.
const CorrectKeyUsage = () => {
  return virtualItems.map(virtualRow => (
    // Using a stable identifier as a key for better performance and fewer bugs
    <div key={virtualRow.id} style={virtualRow.style}>...</div>
  ));
};
This snippet shows the correct way of assigning keys to list items by using stable identifiers (e.g., IDs from your data) instead of the array index. This approach ensures that React can manage updates more efficiently.