To optimize the rendering of React list components, a unique identifier (UID) is required for each list item. This UID lets React identify the item
throughout its lifetime. Avoid array indexes since the order of the items may change, which will cause keys to not match up between renders,
recreating the DOM. It can negatively impact performance and may cause issues with the component state.
function Blog(props) {
return (
<ul>
{props.posts.map((post, index) =>
<li key={index}> <!-- Noncompliant: When 'posts' are reordered, React will need to recreate the list DOM -->
{post.title}
</li>
)}
</ul>
);
}
To fix it, use a string or a number that uniquely identifies the list item. The key must be unique among its siblings, not globally.
If the data comes from a database, database IDs are already unique and are the best option. Otherwise, use a counter or a UUID generator.
function Blog(props) {
return (
<ul>
{props.posts.map((post) =>
<li key={post.id}>
{post.title}
</li>
)}
</ul>
);
}