consider these two examples:
const Item = ({ i }) => <li key={i}>li</li>;
const List = ({ data }) => <ul>{data.map((_, i) => <Item i={i} />)}</ul>;
in this case, you'd get:
Warning: Each child in an array or iterator should have a unique "key" prop.
because li
is not an array item. it's inside of Item
which is an array item.
So key on Item
would eliminate the problem:
const Item = ({ i }) => <li key={i}>li</li>;
const List = ({ data }) => <ul>{data.map((_, i) => <Item key={i} />)}</ul>;
code sandbox: https://codesandbox.io/s/oojwjq0lj6
from docs:
Keys only make sense in the context of the surrounding array.
For example, if you extract a ListItem
component, you should keep the
key on the <ListItem />
elements in the array rather than on the <li>
element in the ListItem
itself.
a note regarding use of Date.now()
:
Keys should be stable, predictable, and unique. Unstable keys (like
those produced by Math.random()) will cause many component instances
and DOM nodes to be unnecessarily recreated, which can cause
performance degradation and lost state in child components.