Rules Hub
Code Ruleset
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
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)
Position-based keys can attach an existing input or component state to a different item after reordering.
Objašnjenje (HR)
Ključevi prema položaju nakon preslagivanja mogu povezati postojeće stanje inputa ili komponente s drugim elementom.
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)
For mapped React children, inspect whether insertion, removal, sorting or filtering can change an item position and whether descendants retain state.
Bilješke (HR)
Za React listu provjeri mogu li umetanje, brisanje, sortiranje ili filtriranje promijeniti položaj elementa i zadržavaju li njegovi potomci stanje.
Exceptions / Tradeoffs (EN)
An index may be acceptable for a fixed, stateless list with no stable identifier. Never generate a new random key during rendering.