Understanding Keys

Keys tell React which list item is which so state and DOM stay correct.

Keys are how React identifies list items between renders. With correct keys, React can add, remove and reorder items while preserving each item's DOM and state.

Why index keys can break

If you use the array index as a key and then insert or reorder items, React reuses the wrong DOM node for the wrong data. This shows up as inputs keeping the wrong value or animations glitching.

Reset state with a key

Changing a component's key makes React discard the old instance and mount a fresh one — a simple way to reset a component's internal state.

Example

Example · javascript
function Profile({ userId }) {
  // Changing the key remounts EditForm, resetting its state
  return <EditForm key={userId} userId={userId} />;
}

function EditForm({ userId }) {
  return <input defaultValue={''} placeholder={'Editing ' + userId} />;
}

When to use it

  • A drag-and-drop task board uses stable database IDs as keys so React preserves the focused input inside each card when a column is reordered.
  • A paginated table resets row components between pages by changing the key to include the page number, forcing React to unmount old rows instead of patching them.
  • A chat list assigns message IDs as keys so new messages are appended without disrupting the DOM nodes — and scroll position — of existing messages.

More examples

Stable ID key on list items

Uses the task's stable database ID as a key so React preserves each li's DOM — including focused inputs — on reorder.

Example · jsx
function TaskList({ tasks }) {
  return (
    <ul>
      {tasks.map(task => (
        <li key={task.id}>
          <input defaultValue={task.title} />
        </li>
      ))}
    </ul>
  );
}

Key to force component reset

Changes the key when userId changes so React unmounts and remounts Profile, clearing all local state.

Example · jsx
function ProfilePage({ userId }) {
  return <Profile key={userId} userId={userId} />;
}

function Profile({ userId }) {
  const [bio, setBio] = React.useState('');
  // fetches and populates bio for userId...
  return <textarea value={bio} onChange={e => setBio(e.target.value)} />;
}

Why index keys break reorder

Contrasts index-based keys that cause stale-state bugs on reorder with stable ID keys that do not.

Example · jsx
// BAD — index key: React reuses DOM nodes incorrectly on reorder
function BadList({ items }) {
  return <ul>{items.map((item, i) => <li key={i}>{item.name}</li>)}</ul>;
}

// GOOD — ID key: correct DOM identity across reorder
function GoodList({ items }) {
  return <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>;
}

Discussion

  • Be the first to comment on this lesson.