الانتقال إلى المحتوى
FrontendReact· 7 دقائق للقراءة

Keys Are Identity, Not a Warning Silencer: Why Index Keys Break Lists

A key tells React which item a row stands for. Use the position, and state follows the position.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

A bug report from the mail team: "I opened an email from Sara. A new email arrived, and now Sara's email is collapsed and the new one is open." Nobody touched the expand logic in months. The list renders with key={index}, added years ago to silence a console warning, and that one attribute is the whole bug.

The common misconception

The belief: keys are a React formality. The console complains when a list has none, any unique value makes the complaint go away, and the array index is unique and always available, so it's the obvious choice.

It's easy to see why it sticks. The warning is the only feedback most people get about keys, so fixing the warning feels like the goal. Index keys also work perfectly in the demo: a static list renders fine, and nothing breaks until an item is added at the top, deleted or sorted. And unique among siblings is a real rule. It's just not the only one: a key also has to keep naming the same item from one render to the next.

What actually happens

Keys answer "which item is this?"

When a list re-renders, React has to pair each new child with one from the previous render. That pairing decides what survives: a matched component keeps its state and its DOM nodes and just receives new props, while an unmatched one is created from scratch. This matching is part of , and among siblings, the is what it matches on. React's docs compare keys to file names in a folder: without names, you'd refer to files by their order, and deleting one would quietly renumber all the rest.

An index key matches by position

If you don't pass a key at all, React uses the index. So key={index} silences the warning and changes nothing else: React still matches "the child at position 0" with "the child at position 0". As long as items never move, position and identity are the same thing. The moment they diverge, state goes with the position:

TSX Inbox.tsx
import { useState } from "react";type Email = { id: string; subject: string; body: string };function EmailRow({ email }: { email: Email }) {  const [open, setOpen] = useState(false);  return (    <li onClick={() => setOpen(!open)}>      {email.subject}      {open && <p>{email.body}</p>}    </li>  );}export function Inbox({ emails }: { emails: Email[] }) {  // Key = position: "the newest email" changes with every arrival  return <ul>{emails.map((email, i) => <EmailRow key={i} email={email} />)}</ul>;}

Walk through the bug. Sara's email is first, so its row has key 0, and you open it: the EmailRow at key 0 now holds open = true. A new email arrives at the top. On the next render, key 0 belongs to the new email, so React reuses the existing component at key 0, keeps its state, and passes it the new email as a prop. The new email shows up open. Sara's email moves to key 1, which used to be the second row's component, with open = false. Nothing was lost or created at random; every piece of state stayed exactly at its position. With key={email.id}, React sees that Sara's key moved to the second place, moves her component there, and creates a fresh, closed row for the newcomer.

The same thing happens to anything a row holds that doesn't come from props: text typed into an uncontrolled <input>, focus, a checked box, a playing animation. Props get updated; everything else sticks to the key.

Where good keys come from

Data from a database already has ids. Data you create in the browser, like a draft note or a new form row, should get an id once, at the moment it's created, and keep it for life:

TypeScript notes.ts
type Note = { id: string; text: string };// The id is born with the item, not during renderexport function createNote(text: string): Note {  return { id: crypto.randomUUID(), text };}

Keys only need to be unique among siblings, not across the app, and your component never receives key as a prop. If it needs the id, pass it separately: <Profile key={id} userId={id} />.

What about content as a key, like the subject line? It holds only while the content is unique and never edited. Two emails titled "Invoice" collide, and editing a note whose text is its key gives it a new key, so React resets that row.

KeyWhat React matches onWhat the user sees
email.id from the dataThe itemState, typed text and focus follow the item
Index, list never reordersPosition, which equals the item hereWorks fine
Index, items inserted, removed or sortedPositionState lands on the wrong item
No key at allPosition, plus a console warningSame as an index key
Math.random() in renderNothing, keys never repeatEvery row rebuilt, input lost

How to apply it in your project

  1. Search for index keysGrep for key={i}, key={index} and key={idx}. For each list, ask whether items can ever be inserted, removed, filtered or sorted, now or after the next feature request.
  2. Key by an id from your dataUse the database id. If items of different types share one list, prefix the id with the type, like order-42 and refund-42, so keys stay unique.
  3. Give local items an id at creationFor items created in the browser, assign crypto.randomUUID() or a counter when the item is created and store it with the item. Never compute the key inside map.
  4. Test with a reorderOpen a row, type into an input, then add an item at the top or sort the list. If the open row or the text moves to a different item, a key is naming a position.

Key takeaways

  • A key names an item, not a slot: it's how React decides which state and DOM belong to which data.
  • An index key is exactly what React does without a key; it silences the warning and nothing more.
  • When items move, index-keyed state stays at its position and shows up on the wrong item.
  • Use stable ids from your data, create ids for local items once, and never generate keys during render.

📚 المصادر

  1. Rendering Lists — React
  2. Preserving and Resetting State — React
  3. Crypto: randomUUID() method — MDN

التعليقات (0)