key
prop JS-0437 135 </thead>
136 <tbody>
137 {data.slice(0, rowCount).map((row, index) => (
138 <tr className="bg-white" key={index}> 139 {Object.values(row).map((cell, cellIndex) => (
140 <td
141 className="px-4 py-2 text-gray-500 truncate"
139 {Object.values(row).map((cell, cellIndex) => (
140 <td
141 className="px-4 py-2 text-gray-500 truncate"
142 key={cellIndex} 143 >
144 {cell}
145 </td>
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.
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} />);
});
cards.map((cardData) => (
<Card key={cardData.id} data={cardData} />
));
buttonData.forEach((btnData) => {
buttons.push(<Hello key={btnData.id} text={btnData.text} />);
});