Rules Hub
Coding Rules Library
Avoid array indices as React keys
Use stable, unique IDs from the data instead of array indices for React keys to ensure correct reconciliation and state preservation.
Bad example
| 1 | const UserList = ({ users }: { users: User[] }) => ( |
| 2 | <ul> |
| 3 | {users.map((user, index) => ( |
| 4 | <li key={index}> |
| 5 | {user.name} |
| 6 | <input defaultValue={user.email} /> |
| 7 | </li> |
| 8 | ))} |
| 9 | </ul> |
| 10 | ); |
Explanation (EN)
Using the array index as a key is unsafe if the list can be reordered, filtered, or mutated. If the order changes, React may incorrectly preserve component state (like inputs) or fail to update the DOM efficiently.
Objašnjenje (HR)
Korištenje indeksa niza kao ključa nije sigurno ako se lista može mijenjati (sortirati, filtrirati). Ako se redoslijed promijeni, React može pogrešno zadržati stanje komponenti (poput inputa) ili neefikasno ažurirati DOM.
Good example
| 1 | const UserList = ({ users }: { users: User[] }) => ( |
| 2 | <ul> |
| 3 | {users.map((user) => ( |
| 4 | <li key={user.id}> |
| 5 | {user.name} |
| 6 | <input defaultValue={user.email} /> |
| 7 | </li> |
| 8 | ))} |
| 9 | </ul> |
| 10 | ); |
Explanation (EN)
Using a stable, unique identifier (like `user.id`) ensures that React can correctly track elements across re-renders, regardless of their position in the array.
Objašnjenje (HR)
Korištenje stabilnog, jedinstvenog identifikatora (poput `user.id`) osigurava da React ispravno prati elemente kroz renderiranja, bez obzira na njihovu poziciju u nizu.
Notes (EN)
Indices are only acceptable if the list is completely static (read-only, fixed length, never reordered). Even then, prefer unique IDs if available.
Bilješke (HR)
Indeksi su prihvatljivi samo ako je lista potpuno statična (samo za čitanje, fiksne dužine, nikad se ne mijenja redoslijed). Čak i tada, preferiraj jedinstvene ID-ove ako su dostupni.