QReact · Interview preparation
When is an array index a safe React key?
An index is usually acceptable only when the list is fixed and its items are never inserted, deleted, or reordered.
The idea to remember.
An index is usually acceptable only when the list is fixed and its items are never inserted, deleted, or reordered. Prefer a stable identifier from your data whenever users can change the list.
01Learn by doing
From first example to real project.
Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.
Basic: a stable list
01 / BEGINNERA stable ID lets React keep each row's identity.
const todos = [{ id: 1, text: 'Read docs' }, { id: 2, text: 'Build app' }];
function TodoList() {
return <ul>{todos.map(todo => <li key={todo.id}>{todo.text}</li>)}</ul>;
}Intermediate: intentional reset
02 / INTERMEDIATEChanging a key tells React this is a new form, so its local state resets.
function ProfileEditor({ person }) {
return <ProfileForm key={person.id} person={person} />;
}Real scenario: reorderable tasks
03 / REAL SCENARIOUse database IDs, not array positions, when tasks can move.
function TaskBoard({ tasks, onMove }) {
return tasks.map(task => (
<TaskCard key={task.id} task={task} onMove={() => onMove(task.id)} />
));
}02Check your understanding
Try it in your own words.
Explain when is an array index a safe React key without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.
Keep learning here.
Explore more in-depth guides, exercises and related interview questions in this library.
Browse React study guides ↗