liveBook · Manning

Keyed list

As explained in Build a Frontend Web Framework (From Scratch)

A list-rendering pattern in which items are identified by keys so that their corresponding interface nodes can be tracked across updates.

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

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Explains identity failures through counter examples and an index-key case, without detailing a complete reconciliation implementation.
Examples
Uses stateful counters, virtual DOM snapshots, component movement, and loop-generated lists to demonstrate key behavior.
What it assumes
Assumes familiarity with virtual DOM nodes, rendering lists, components, and reconciliation; teaches why hidden component state requires identity.
What you can do after
Apply it via stable unique key attributes when rendering changing lists of components or elements.
How it connects
Connects keys with virtual DOM, reconciliation algorithms, components, elements, props, and internal component state.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.