🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

List Keys and Reconciliation: Why Identity Matters

React FundamentalsListsđŸŸĸ Free Lesson

What You'll Learn

  • 1Describe how React pairs old and new children during reconciliation
  • 2Reproduce the state corruption caused by array indices used as keys
  • 3Choose an identifier strategy for remote, generated, and compound data
  • 4Diagnose a list bug where state appears attached to the wrong item

What a key identifies

Rendering a list looks like a loop, but React treats the output as an ordered set of children that must be matched against what is already on screen. The key is the name tag it uses for that matching. Without one, React falls back to position: the first child in the new array is assumed to be an update of the first child in the old array, and so on down the line.

That positional assumption is correct for static markup and wrong the moment the list can change shape. Reorder, insert, or remove an item and the positions no longer describe the same rows, so React updates the existing components in place instead of moving them. Each of those components holds its own state, its own refs, and its own subscription handles, all of which follow the component instance rather than the data. The visible symptom is a checkbox that toggles the wrong row, an input that keeps the previous row's text, or an animation restarting on every item.

The contract is simple to state: a key must be stable for the lifetime of an item and unique among its siblings.

How the diff pairs children

React walks both arrays of children in order and compares keys as it goes. A key present in both lists becomes an update, so the existing component instance is reused with new props. A key that appears only in the new list is mounted fresh. A key that disappeared is unmounted. Nothing in that description mentions position, which is why a correct key set turns a reorder into a cheap set of prop updates instead of a full remount.

function Playlist({ tracks, onRemove }) {
  return (
    <ol>
      {tracks.map((track) => (
        <li key={track.id}>
          <span>{track.position}. {track.title}</span>
          <button type="button" onClick={() => onRemove(track.id)}>
            Remove
          </button>
        </li>
      ))}
    </ol>
  );
}

Because each row is keyed by a durable id, moving a track to the top reuses the same component instance and its local state, such as an expanded description or a hover highlight. React updates the surrounding markup and leaves the row's internals alone, which is both faster and correct.

The index bug, reproduced

The tempting shortcut is using the array position as the key. It works in the demo, where the list only ever grows, and fails in production, where lists are filtered, sorted, and edited.

// Broken: position masquerades as identity
function BrokenList({ items }) {
  const [draft, setDraft] = useState('');
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>
          <input
            value={item.text}
            onChange={(e) => item.onEdit(item.id, e.target.value)}
          />
          <span>{item.tag}</span>
        </li>
      ))}
      <li>
        <input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Add item" />
      </li>
    </ul>
  );
}

Delete the first row and every surviving component keeps its position-based key, so React pairs the old second row with the new first slot. The inputs retain the previous contents by position rather than by identity, and the row you deleted appears to come back as a ghost. Adding a temporary row above the list has the same effect in reverse. The fix is not a different state hook; it is giving React a name for each item that does not depend on where it sits.

Choosing an identifier

The best key depends on where the data comes from, and the answer is almost always something already in the record.

Data sourceGood keyWhy
Rows from a databaseThe primary key columnDurable, unique, and already meaningful
Records from an APIThe resource id or a versioned idSurvives pagination and refresh
Locally created itemsA generated id from a counter or uuid libraryCreated once at insertion, never recomputed
Static configuration arraysThe index, or a name fieldNothing is inserted or reordered, so position is stable
Derived rows, such as grouped recordsA composite of the group and row idsKeeps uniqueness across groups
A character or word in a text editorIts offset or a content-addressed idOffsets shift as text edits, so prefer a content id when possible

If the data truly has no stable identifier, generate one when the item enters your state rather than when it renders. Computing a random key during render gives every row a new identity on every commit, which is the most expensive possible failure mode: the whole list remounts constantly.

Keys, fragments, and nested structure

A key is scoped to its siblings, which trips people up in two places. When a component returns a fragment with several children, the fragment itself needs a key if it sits in a list, and the keys inside it must not collide in ways that make React guess. Similarly, when a mapped row renders a sub-list, the inner list needs its own key namespace; ids that are unique per row but reused inside each row produce confusing collisions.

Nested lists also tempt developers into concatenating keys, such as combining a parent id and a child id with a separator. That works, but a composite string is only as reliable as the uniqueness of its parts, and a separator that can appear inside either part quietly breaks the guarantee. Prefer an object that carries a precomputed id, or build the composite in a helper you test once.

Debugging state that appears on the wrong row

When state follows position instead of identity, three checks isolate the problem quickly. First, confirm every key in the list is unique and stable by logging the key set on each render and comparing consecutive sets. Second, reproduce the failure with the smallest possible list, usually two rows plus a delete, because the bug rarely shows itself with ten items. Third, look for state that lives above the row when it should live inside it: a filter string held by the parent and passed down as a value prop is not affected by keys at all, so the problem is elsewhere.

A useful bisect is to replace the row component with a version that renders only its key. If the ghost state disappears, the identity problem is confirmed. If it remains, the value is being derived from position somewhere higher in the tree, often a default value computed from the array index during render.

What correct keys save you

Identity is not only about correctness; it is also about the amount of work a list update costs. When keys are stable, React reuses the existing component instances for the rows that survived the change, so a reorder updates a handful of props and text nodes instead of mounting and unmounting every row. For a list with expensive children, such as rows containing charts, editors, or embedded media, that difference is the entire performance budget.

The saving is conditional on the rest of the row being equally stable. A correctly keyed list whose rows receive a new object or an inline callback on every render will still re-render every row, because the instance is reused but the props are not equal. Keys get React to the right instance; memoisation and stable callbacks decide whether that instance does any work. Fixing the keys first is still the right order, because memoising a list that remounts on every change protects nothing.

Common Mistakes

Using the array index as the key of a list that can be reordered, filtered, or prepended to

Fix: Key by a durable id, or generate one when the item enters state

Generating a fresh id during render so the key changes on every commit

Fix: Create the identifier once, at insertion time, and store it with the record

Concatenating ids with a separator that can appear inside either part

Fix: Use a composite that cannot collide, or an object that already carries a unique id

Assuming a list bug must be a state bug before checking the keys

Fix: Log the key set across two renders; identity problems are usually visible there first

Best Practices

  • Treat the key as part of your data model rather than as a rendering detail
  • Generate ids at the moment an item is created, never while rendering
  • Keep a single source for key values so list, detail view, and tests agree
  • Reorder lists with the same id values so React moves instances instead of recreating them
  • Audit lists that support deletion first; they expose key bugs faster than any other feature

Key Takeaways

  • React pairs list children by key, not by position, and reuses instances accordingly
  • Component state follows the instance, so wrong keys attach state to the wrong data
  • Indices are only safe for static arrays that never reorder or shrink
  • Durable ids come from the database, the API, or an insertion-time generator
  • When state appears on the wrong row, check the keys before rewriting the state logic
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement