Why list items need unique key, but other not, in react?

Why do rendering list items need to pass a key prop while other elements don’t?

For example, if I do like –

['apple', 'orange', 'lemon'].map((fruit, i) => {
    return <li key={i}>{fruit}</li>;
});

The snippet before needs to pass the key={i} prop, But if I do the same job like-

<ul>
  <li>apple</li>
  <li>orange</li>
  <li>lemon</li>
</ul>

In this case, we don’t need to use the key prop.

So, the question is why we need the key prop in the 1st case and why not in the 2nd case?

Answer

The React official documentation talks about keys here, among other places. Here’s the key (no pun intended) quote:

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

When you are rendering an array of elements, and that array may change, or the elements inside the array may change, supplying a key helps React to figure out which element in the array it should be updated. Not supplying a key can introduce bugs when React gets confused about which element it should be updating.

Your second example doesn’t require a key because nothing is changing — it’s just a couple static elements, so there’s no risk of React getting confused about what to update.