DEV Community

Cover image for Benefit of 'key' prop in React
Prathamesh Patil
Prathamesh Patil

Posted on • Updated on

Benefit of 'key' prop in React

If you are a beginner in a react js you may have encountered the key warning in the console while listing elements on the page in a loop.

KEY is a very important and useful concept in react js in improving user experience

Now the question is how?? -- Refer the image below

Alt Text

In the image above on the left side, we have a list were 2 elements are rendered, then now
we add the third element at end of the list as shown at right, react will compare both and will get to know that it needs to update only the third element in the list.

Alt Text

But if we add the element at first position as shown in image above(Diana added th list) the react match will fail and it re-render all list again.
to avoid this re rendering, we can use the "key" prop in the list which will keep track and update only elements that are new. as shown in the below image. ..so simple :)

Alt Text

Top comments (2)

Collapse
 
codenamejason profile image
Jaxcoder

Simple and to the point. On bigger data-sets this would make a generous performance difference, no?

Collapse
 
pratham0182 profile image
Prathamesh Patil

Yes it will 🙂