Keys help React identify which items have changed, been added, or removed, enabling efficient updates to the DOM.
Keys are a special attribute you need to include when creating lists of elements in React. They give React a way to identify which items in a list have changed, been added, or been removed between renders.
Without keys, React would have to re-render the entire list when any item changes. With proper keys, React can match elements between the old and new trees, preserving state for unchanged elements and only updating what's necessary.
Keys should be stable, predictable, and unique among siblings. Using array indices as keys is generally discouraged because it can cause issues when the list order changes—React might reuse the wrong component instance, leading to bugs with state preservation.
The ideal key is a unique identifier that comes from your data, such as a database ID. If your data doesn't have unique IDs, you might generate them when the data is created (not during render, as that would create new keys every render). Keys only need to be unique among siblings, not globally unique across your entire application.
Keys help React identify which items have changed, been added, or removed, enabling efficient updates to the DOM.
Join our network of elite AI-native engineers.