๐Ÿ”‘ What is key in React?

Whenever you render a list in React, you need to assign a key to each item:

const items = ['๐Ÿš€', '๐Ÿ”ฅ', '๐Ÿ’ป'];
items.map((item, index) => (
   {item} 
));

At first glance, using the index as the key seems fine...

But hereโ€™s the truth: this can lead to subtle UI bugs and performance issues when items are added, removed, or reordered.


๐Ÿ’ฅ Why?

React uses key to:

  • Identify which items have changed
  • Reuse DOM elements efficiently
  • Avoid unnecessary re-renders

When keys are unstable (like shifting indexes), React gets confused and might:

  • Update the wrong component
  • Lose input focus
  • Animate incorrectly

โœ… The Better Way

const items = [
  { id: 1, emoji: '๐Ÿš€' },
  { id: 2, emoji: '๐Ÿ”ฅ' },
  { id: 3, emoji: '๐Ÿ’ป' },
];

items.map(({id, emoji}) => (
  
     {emoji} {console.log(id)}
  
));

๐Ÿง  This way, each item has a stable identity. React can now confidently handle changes without weird UI glitches.


๐Ÿšจ Summary

  • Donโ€™t just use index for the sake of removing a warning.

  • Use unique and stable keys to unlock Reactโ€™s full rendering power.

  • This small habit will save you from big bugs later!


๐Ÿ’ฌ Did this clarify something for you?

Let me know in the comments โ€” or just drop a ๐Ÿ”ฅ if youโ€™ve learned something new!

Click ME to get the original post on LinkedIn.

code