React warning: Each child in a list should have a unique "key" prop
asked 5 months ago650 viewsen
5
{todos.map((t, i) => <TodoItem todo={t} />)}
I get the key warning. If I use key={i} it goes away. Is the index OK as a key?
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
asked 5 months ago
Marie Louis 2.2k
1 Answer
5
✓✓ Accepted answer
React uses key to match list items between renders. Use a stable, unique id from your data:
{todos.map(t => <TodoItem key={t.id} todo={t} />)}
The index is only safe if the list is never reordered, filtered, or inserted into. Otherwise React reuses the wrong component instance, and you get bugs like an input keeping the text of the item that was deleted.
If your items have no id, generate one when you *create* the item (crypto.randomUUID()), not during render.
Sign in to tell others whether this worked.
answered 5 months ago
Jean Pierre 5.1k
Sign in and verify your email to post an answer.