๐ 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
indexfor 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.
