Do not use Array index in keys
20 return (
21 <Card>
22 {values.map((value, index) => {
23 return <options.itemComponent key={index} item={value}/>;24 })}
25 {values.length === 0 && (
26 <Stack align={"center"} mb={"xl"}>
Description
When rendering a list of items in React, it is necessary to pass a "key" prop.
This key is used by React to identify which items have changed, are added, or are removed and should be stable.
It is not recommended to use the index of an element as key
because it doesn't uniquely identify the element.
When elements are added/removed from an array, the index of an element may change, which will result in unnecessary re-renders.
When the array is sorted, or an element is added to the beginning of the array, the indices will be changed even though the element representing an index may stay the same. This too can result in unnecessary renders.
Bad Practice
cards.map((cardData, index) => (
<Card key={`key-is-${index}`} data={cardData}/>
));
buttonNames.map((btnText, index) => (
<Button key={index} text={btnText}/>
));
things.forEach((thing, index) => {
otherThings.push(<Hello key={index} />);
});
Recommended
cards.map((cardData) => (
<Card key={cardData.id} data={cardData} />
));
buttonData.forEach((btnData) => {
buttons.push(<Hello key={btnData.id} text={btnData.text} />);
});