What is "key" prop and what is the benefit of using it in arrays of elements?
Assesses fundamental understanding of React conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
A key is a special attribute you should include when mapping over arrays to render data. _Key_ prop helps React identify which items have changed, are added, or are removed.
Keys should be unique among its siblings. Most often we use ID from our data as _key_:
```jsx harmony
const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li>);
When you don't have stable IDs for rendered items, you may use the item _index_ as a _key_ as a last resort:
jsx harmonyconst todoItems = todos.map((todo, index) => (
<li key={index}>{todo.text}</li>
));
```
Benefits of key:
- Enables React to efficiently update and re-render components.
- Prevents unnecessary re-renders by reusing components when possible.
- Helps maintain internal state of list items correctly.
Note:
- Using _indexes_ for _keys_ is not recommended if the order of items may change. This can negatively impact performance and may cause issues with component state.
- If you extract list item as separate component then apply _keys_ on list component instead of
litag. - There will be a warning message in the console if the
keyprop is not present on list items. - The key attribute accepts either string or number and internally convert it as string type.
- Don't generate the key on the fly something like
key={Math.random()}. Because the keys will never match up between re-renders and DOM created everytime.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.