Recently i came across a Linkedin post about use case of keys in react without specifying the details under the hood. Hence decided to decode it out in this post. Now Let's see what's happening under the hood of react when we add keys to our list.
Ever wonder how react detect the Dom has been updated? React uses the state of art diffing algorithm to do reconciliation. And do you know it have o(n) complexity?
The algorithm follows this two basic principle
1.Two elements of different types will produce different trees.
2.The developer can hint at which child elements may be stable across different renders with a key prop.
Ok how this helps out us, lets take one example DOM list
<ul>
<li>1</li>
<li>2</li>
</ul>
Now let's say you want to add one item at the start.
<ul>
<li>3</li>
<li>1</li>
<li>2</li>
</ul>
Now react will compare both this Dom and have to iterate then have to figure out both the list item 1 and list item 2 have been not changed. Then have to add the list item 3 at start.
Let's just imagine if our list have 1000 of elements which need to be updated frequently. Our app would be have a worst performance nightmare.
Now lets see how this works differently when you add a key
<ul>
<li key='a'>3</li>
<li key='b'>1</li>
<li key='c'>2</li>
</ul>
Now when react compare the Dom, it exactly knows a has been introduced newly and no change has happened on b and c so it will just add the a list item in the list. In this way it will avoid iteration as well.
Also make sure you are not keeping the index as key which is not recommended by react as it might result in unexpected re-render behaviours. Make sure to use unique key elements always.
Hope now it's clear that why adding a key would be very important in react and how it can improve the performance so well.
you can check more about the diffing algorithm here
Top comments (0)