React
react/no-array-index-key
A list item's key comes from the data (an id), not from the array index.
moderatestaticfe-react
Why
React matches list items between renders by key. With the index as key, inserting, removing or sorting items gives each component the state of its neighbour: typed text, checked boxes and focus move to the wrong row.
Fix
Use a stable id from the data: key={todo.id}. If the data has none, create ids when the data is created (crypto.randomUUID()), not during render. The index is acceptable only for a static list that never reorders and holds no state.
Examples
// bad
{todos.map((todo, index) => <Todo key={index} todo={todo} />)}
// good
{todos.map((todo) => <Todo key={todo.id} todo={todo} />)}Sources
Facts
- Id
react/no-array-index-key- Severity
- moderate
- Check
- static checked in the source by
audit - Applies to
jsx- Only in projects with
reactnextpreact- Taught by the skill
fe-reactReact components- Since version
- 0.1.0
Read it in the terminal
npx github:dawidolko/frontend-skills explain react/no-array-index-key