Why React need the "key" attribute?

Why React need the "key" attribute?

Reconciliation in ReactJS

Did you ever encounter this warning while creating a React App?

Do you know why a React app expects a "key" prop/attribute?

code.png

It's due to the Reconciliation algorithm of React.

As we know, when React re-renders, it compares the previous props with the upcoming props, and whatever differences are there, it gets applied to the DOM tree.

Now consider an example where the same child elements are for different DOM nodes.

example2.png

As in the above example, there are two different nodes with almost the same child elements to be rendered.

By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference.

React will match the two ReactJS "li" element subtrees, match the two Angular "li" element subtrees, and then insert the VueJS "li" element subtree.

But this implementation is efficient only if the order of child elements in the two DOM nodes is maintained.

If someone naively implements it like below,

example3.png

then the React will mutate every child instead of realizing it can keep the ReactJS "li" element and Angular "li" element subtrees intact. This inefficiency can be a problem.

Thus this calls for a solution that tells React which subtrees should be intact when rendering.

To solve this issue, React supports a key attribute. When children elements have keys, React uses the key to match the children in the original tree with the children tree in the subsequent tree.

example.png

In short, when keys are present in DOM elements, React can compare them and renders the mutations only, irrespective of the order of child elements.

Now React knows that the element with key 'vueJS' is the new one, and the elements with the keys 'reactJS' and 'angular' have just moved.

Ref: Reconciliation in ReactJS