Keys are used for keeping track of individual components within collections so that they can be identified easily and manipulated efficiently without causing unnecessary duplication or confusion among elements.
Here is an example of a list of items that have unique keys:
import React, { Component } from 'react';
class MyList extends Component {
render() {
const items = [
{ id: 1, text: 'Item x' },
{ id: 2, text: 'Item y' },
{ id: 3, text: 'Item z' },
];
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}
}
export default MyList;
In this example, the list of items is rendered using the map function. Each item has a unique id property that is used as the key. The key is passed to the li element using the key attribute.
A key should be
● unique among its siblings
● stable and predictable
It is not recommended to have an array index as a key as they are not identifiers since the index changes when an element is added or removed from the array.Instead, you should use a unique identifier that is stable and predictable, such as the item's ID or unique property.