Skip to content
react questions

React · 7 of 13middle~1 min

Explain the reconciliation algorithm and the role of keys.

#core#performance

Reconciliation and keys

The reconciliation algorithm

React compares the old and new virtual trees using two rules:

  1. Different element types - the old tree is destroyed and a new one is mounted.
  2. 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.

key is also used as an intentional state reset - changing a component's key fully recreates it.

updated

did you know it?

read more on the blog

view all

related questions