
Keys Are Identity, Not a Warning Silencer: Why Index Keys Break Lists
- كاتب موثّق
- React 19
محتويات المقال
key={index}, added years ago to silence a console warning, and that one attribute is the whole bug.
The common misconception
What actually happens
Keys answer "which item is this?"
An index key matches by position
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:
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>;}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 = identity: the open state follows the email wherever it moves return <ul>{emails.map((email) => <EmailRow key={email.id} email={email} />)}</ul>;}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.
<input>, focus, a checked box, a playing animation. Props get updated; everything else sticks to the key.
Where good keys come from
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 };}key as a prop. If it needs the id, pass it separately: <Profile key={id} userId={id} />.
email.id from the data | ||
Math.random() in render |
How to apply it in your project
Search for index keys Grep for key={i},key={index}andkey={idx}. For each list, ask whether items can ever be inserted, removed, filtered or sorted, now or after the next feature request.Key by an id from your data Use the database id. If items of different types share one list, prefix the id with the type, like order-42andrefund-42, so keys stay unique.Give local items an id at creation For 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 insidemap.Test with a reorder Open 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.
التعليقات (0)