Master React Lists and Keys
Rendering lists in React is simple, but doing it right is hard.
Many developers use the array index as a key. This is a mistake. It leads to bugs and slow performance.
Here is how you should handle dynamic data in React.
How React Uses Lists React uses the map() method to turn arrays into UI elements. When you use map(), React transforms each piece of data into a component.
The Role of Keys React uses a Virtual DOM. When data changes, React compares the new data with the old data. This process is called reconciliation.
Keys act as unique identifiers. They tell React exactly which item changed, moved, or was deleted.
Why Using Index as a Key is Dangerous Using the index (0, 1, 2...) as a key causes three main problems:
- Component State Errors: If you sort a list, input fields or checkboxes might show data from the wrong item.
- Performance Drops: React cannot track which item is which. It often re-renders the entire list instead of just one item.
- Visual Bugs: Your UI might look correct, but the internal logic will fail when items shift.
The Right Way to Use Keys To keep your app fast and stable, follow these rules:
- Use Unique IDs: Always use IDs from your database (like a UUID or a primary key).
- Never Use Math.random(): Generating keys during render causes React to recreate every single element on every update. This kills performance.
- Keep Keys Stable: A key must stay the same for the same piece of data for its entire lifecycle.
Comparison at a Glance
Feature: Stability Using Index: Unstable Using Unique ID: Highly Stable
Feature: Performance Using Index: Poor Using Unique ID: Optimal
Feature: State Safety Using Index: Unsafe Using Unique ID: 100% Safe
Summary for Developers Use the map() method. Pass a unique, stable ID to the key prop. Avoid using the array index for any list that can change, sort, or filter.
