React uses keys to preserve the identity of list items between renders. When a list item is inserted, removed, or reordered, using the array index as the key can make React associate the wrong DOM node or component instance with an item. This can mix up input values, focus, and component-local state.
function Blog(props) {
return (
<ul>
{props.posts.map((post, index) =>
<li key={index}> <!-- Noncompliant: Reordering 'posts' can preserve the wrong state on the wrong item -->
{post.title}
</li>
)}
</ul>
);
}
To fix it, use a string or a number derived from the data that identifies the item. The key must be stable across renders and unique among siblings.
If the data comes from a database, database IDs are usually the best option. Otherwise, create the ID when the item is created and store it with the data. Do not generate a new key while rendering.
function Blog(props) {
return (
<ul>
{props.posts.map((post) =>
<li key={post.id}>
{post.title}
</li>
)}
</ul>
);
}