DEV Community

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

Posted on • Edited on

10 6

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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 🙂

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay