Sphere
Log in Join
☆ 5

index as key scrambles input values in a React list

React 18 list of editable rows. I used index as the key. When I delete a row in the middle, the values in the following rows jump to the wrong inputs. Type a in row 2, delete row 1, and a now appears in row 1. I know index-as-key is bad but I did not think it would corrupt input state like this instead of just re-rendering. Why exactly?

⚑ Report

4 replies

☆ 0
P pg ·2026-10-23#1

React reuses DOM nodes by key. With index keys, deleting row 1 makes old row 2 become index 1, so React reuses that input element for the new data. Uncontrolled inputs keep their DOM value, so the text stays put while the data underneath changes. That is the corruption you are seeing.

⚑ Report
☆ 0
J json ·2026-10-30#2

That is exactly it. Switched the key to row.id, a UUID from the server, and the problem vanished immediately. I feel like we should have caught this in code review, the lint rule for index keys was disabled because someone had a stable list argument.

⚑ Report
☆ 0
G graf ·2026-10-30#3

Stable lists are the one case index keys are fine, but the moment you can delete or reorder, they are not stable anymore. We enable react/no-array-index-key as an error and only suppress it with a comment when we genuinely have a fixed list.

⚑ Report
☆ 0
P paper31 ·2026-11-07#4

If you cannot get an id from the backend for some reason, generate one client-side when the row is created and keep it in the row object. Just do not regenerate it on every render or you will defeat the purpose.

⚑ Report
Log in to reply.