Reconciliation and keys
The reconciliation algorithm
React compares the old and new virtual trees using two rules:
- Different element types - the old tree is destroyed and a new one is mounted.
- Same types - only changed attributes/props are updated.
Why keys are needed
When rendering lists React uses key to identify elements between renders.
tsx
// Bad - React may mix up elements
items.map((item, index) => <Item key={index} {...item} />)
// Good - stable unique identifier
items.map((item) => <Item key={item.id} {...item} />)What happens with wrong keys
- Unnecessary unmount/mount instead of update.
- Loss of component state.
- Broken animations.
keyis also used as an intentional state reset - changing a component'skeyfully recreates it.
updated
did you know it?