I'm a newbie to React and trying to understand key
attribute of components.
According to the official documentation (emphasis mine),
You might be tempted to use an item’s index in the array as its key. In fact, that’s what React will use if you don’t specify a key at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.
but what kind of bugs can appear in addition to performance issue?
I'd like to see a concrete example code which is buggy due to the lack of key
attribute, rather than an abstract textual explanation like "it would be buggy".
For example, the code below works as expected without the use of key
(CodeSandbox):
import {useState} from "react";
export default function MyApp() {
const [l, setL] = useState([
{
id: 0,
name: "Apple",
},
{
id: 1,
name: "Orange",
},
{
id: 2,
name: "Grapes",
},
]);
return (
<>
<ul>
{
l.map(e => {
return (
<div>
<li>{e.name}</li>
<button onClick={() => {
const index = l.indexOf(e);
let ll = [...l];
ll.splice(index, 1);
setL(ll);
}}>x</button>
</div>
);
})
}
</ul>
</>
);
}