Keys in React from a performance perspective

Keys in React from a performance perspective

The concept of rendering list of data in React is:

“React should be able to update and render lists efficiently, without performance losses, or bugs.” In order to React do that, you should assign a key attribute to the list items

The Keys help React identify which items have changed, added, or removed.


What if you don’t add the “key” attribute?

React will see all list items similar

In case the array changed:

  1. All items will be visited and updated, React will render an additional div at the end, and walks through all the items to update the content inside of every item to match the array content again.
  2. The final result is correct, but from a performance perspective this is not great.
  3. It can lead to bugs. If the items are state full items
  4. You will see a warning message in the console to add “key” prop

No alt text provided for this image
warning message in the console to add “key” prop


Can we use the “index” as a key ?

You can use the index as a key in case you have a list with static data that is never reordered or filtered.

Otherwise, it’s not recommended using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.

Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. Where he mentioned that “It may break your application and display wrong data!”

No alt text provided for this image
Robin Pokorny’s article

I hope I could explain why adding a key prop to your list items matters. Thanks!

#reactjs #performance

To view or add a comment, sign in

More articles by Leen Shehadeh

Explore content categories