A key is a special string attribute you need to include when creating lists of elements. Keys help React identify which items have changed, are added, or are removed.
For example, most often we use IDs from your data as keys
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
);
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:
const todoItems = todos.map((todo, index) =>
<li key={index}>
{todo.text}
</li>
);
Note:
- We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state
- If you extract list item as separate component then apply keys on list component instead li tag.
There will be a warning in the console if the key is not present on list items.