Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Key uniqueness on different elements

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?

like image 441
Kousha Avatar asked Jun 13 '16 18:06

Kousha


Video Answer


1 Answers

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

like image 128
omerts Avatar answered Oct 16 '22 00:10

omerts