A keyed list gives each rendered item a stable identity, allowing the reconciliation algorithm to track the corresponding interface node across updates. This matters most for stateful components: their internal state is not visible in the virtual DOM, so position alone cannot identify them. section 12.0
Use keys with these responsibilities:
- Give every component in the list a unique key so the reconciliation algorithm can distinguish its instances. section 12.0 section 12.6
- Keep each key invariant across renders and throughout the node’s lifecycle, even when items move. section 12.3.1
- Avoid using the list index as a key; insertion, removal, or movement can change positions and misidentify stateful components. section 12.3.1 section 12.6
- Keys are optional for element lists, but they can reduce unnecessary reconciliation work. section 12.6
Removing the middle counter
Three counters may render with different hidden count states. If the middle counter is removed, stable keys let the remaining component instance move into its new position instead of causing the algorithm to mistake the last counter for the removed one. section 12.0 section 12.3.1
h('div', {}, [
h(Counter, { initialCount: 0 }),
h(Counter, { initialCount: 1 }),
h(Counter, { initialCount: 2 }),
])
Inspect a small component list whose instances carry different initial state values, then compare it with the keyed-update problem. section 12.0
