Ad

Why Can I Avoid Using Keys When Using Fragments But Not When Using Arrays?

- 1 answer

I made an example here: http://jsbin.com/divubozaha/edit?js,console,output

Basically, this has no warning:

<div>
  <h1>test1</h1>
  {Math.random() > 0.5 ? <h1>test1</h1> : null}
  <h1>test1</h1>
</div>

(even when some of the child can be re-ordered.

But this triggers the infamous Each child in an array or iterator should have a unique "key" prop.:

<div>{[
  <h1>test2</h1>,
  <h1>test2</h1>,
  <h1>test2</h1>
]}</div>

So, when filtering the children of an element, I have the warning. Maybe there's some kind of implicit keys in the fragments ?

Ad

Answer

The implicit key is the order in which the element appears relative to its siblings. i.e. 0, 1, 2... You can see this in the React dev tools: it's the last digit of the data-reactid attribute.

The purpose of the key is to optimise Virtual DOM diff-ing. The problem with arrays is that they're dynamic. If you have an array that generates elements [ A, B, C, D, E ] and then remove the first item, your new elements become [ B, C, D, E ]. React will then compare B to A, C to B, D to C, E to D and change every single node.

If instead you provide a key to identify each element uniquely, React will know that A has been removed and will then compare B to B, C to C, D to D and E to E. This allows for a more efficient DOM change.

React generates this warning because it knows how unreliable implicit array keys are. It's asking you for some optimisation help. Your first snippet is also an example of unreliable implicit keys. But it's more of an edge case.

Ad
source: stackoverflow.com
Ad