Is the following considered unique key in React?
<span>
{someArray.map(function (a, index) {
return (
<span key={index}>{a}</span>
);
})}
</span>
<span>
{someArray2.map(function (a, index) {
return (
<span key={index}>{a}</span>
);
})}
</span>
In this case, both imbedded span
inside the loops will have the same key, but they are children of different parents. Is this alright?
Yes it does count as unique. React uses keys in its reconciler, in order to decide how to mutate the DOM in the most efficient way.
In general, the problem keys solve, is identifying nodes in the same hierarchy (sibling nodes), between renders.
For example, if you have:
// render A
<div class='parent'>
<div>one</div>
</div>
// render B
<div class='parent'>
<div>two</div>
<div>one</div>
</div>
In the second render, there is no cost-effective way of knowing that <div>one</div>
hasn't changed, and all we need to do is add a <div>two</div>
before it. If <div>one</div>
had a key, by comparing keys across renders, we could know it already existed in previous render, and all we need to do is add <div>two</div>
before.
From the react docs:
Remember that the key only has to be unique among its siblings, not globally unique
For further reading: https://facebook.github.io/react/docs/reconciliation.html#keys
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With