Learning on Web Dev Open is free for all.

Framework Internals > Components as contractsLists, keys and identity, again
Phase 04Components as contracts195 of 434

Lists, keys and identity, again

You implemented the diff, so you already know why this matters. Here is what it looks like when it bites in React specifically.

Concept11 minAI pair

The key must be stable across renders, unique among siblings, and derived from the item rather than its position. A database id is ideal. A composite of fields that together identify the row is fine. Math.random() is a fresh identity every render, which means a full remount of the list every time and the loss of any state inside it.

For genuinely id-less client-side data, generate an id when you create the item, crypto.randomUUID() at insertion time, and store it alongside. Deriving one from content at render time breaks the moment two items have the same content, which is more often than you would like.

The deliberate use is worth knowing: putting a key on a component to force it to remount when the key changes. <EditForm key={recordId} /> resets all internal state when you select a different record, which is exactly right and much cleaner than an effect that watches recordId and clears six pieces of state by hand.

You should now be able to

  • Choose a stable key for data with no natural id
  • Use a key deliberately to force a remount
Ask the community

Loading…