You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
In React, the key prop is a special identifier used internally by React to optimize rendering and correctly manage component updates.
It is not passed as a normal prop to components and cannot be accessed inside them.
🎯 Why key Exists
React uses a process called reconciliation to determine:
what changed
what should be updated
what can be reused
key helps React identify elements between renders.
Without stable keys, React may:
re-render unnecessary elements
preserve the wrong component state
produce unexpected UI behavior
📦 Common Usage: Lists
The most common use case for key is rendering lists.
{items.map(item => (
))}
Here, key allows React to:
track each item independently
update only what changed
avoid full re-renders
🔄 key and Component Lifecycle
React decides whether to:
update an existing component
or destroy and recreate it
based on the key.
Same key
component is preserved
state is kept
effects are not reset
Different key
component is unmounted
component is remounted
state is reset
CSS animations restart
Changing a key forces remount, not just re-render.
This means:
all internal state is lost
lifecycle hooks restart
DOM is recreated
This behavior is intentional and part of React’s design.
🎨 Valid Use Cases for Changing key
Using a changing key is acceptable and recommended when:
the component is purely visual
no internal state must be preserved
remounting is desired
Examples:
notification badges
animated icons
loading indicators
step-based UI transitions
🚫 Anti-Patterns
Avoid:
key={Math.random()}
key={Date.now()}
key={index}
Why?
causes unnecessary remounts
breaks state persistence
hurts performance
creates unstable UI behavior
🧠 Best Practices
Keys should be:
stable
predictable
unique within the list
Prefer IDs from data
Use changing keys only when remounting is intentional
🏁 Summary
key is a reconciliation hint, not a prop
Stable keys preserve components
Changing keys force remount
Remounting is powerful but should be used deliberately
Ideal for controlled UI resets and animations
All reactions