The key prop is crucial for React's reconciliation algorithm. Here's how to use it correctly.
Why Keys Matter#
Choosing Keys#
Index Keys Pitfalls#
Generating Keys#
Keys with Fragments#
Keys for Component Reset#
Reconciliation Deep Dive#
Performance Implications#
Common Mistakes#
Best Practices#
Key Selection:
✓ Use unique IDs from data
✓ Generate IDs when items are created
✓ Use stable, predictable values
✓ Keep keys unique among siblings
When Index is OK:
✓ Static, never-reordered lists
✓ Items have no state
✓ Items are never filtered/sorted
✓ List is not editable
Performance:
✓ Combine with React.memo
✓ Use stable object references
✓ Avoid computing keys expensively
✓ Profile with React DevTools
Avoid:
✗ Random values as keys
✗ Index keys for dynamic lists
✗ Changing keys unnecessarily
✗ Duplicate keys in same list
Conclusion#
Keys are essential for React's efficient list rendering. Use stable, unique IDs from your data, avoid index keys for dynamic lists, and leverage keys to force component remounts when needed. Proper key usage improves performance and prevents subtle bugs.