Consider a React component rendering a list of items. What is the main reason React requires a unique key prop for each list item?
Think about how React updates the screen when data changes.
Keys help React track items between renders. Without keys, React can't tell which item changed, so it may re-render unnecessarily or incorrectly.
Given this React code snippet rendering a list without unique keys, what is the likely outcome when the list changes?
const items = ['apple', 'banana', 'cherry'];
return items.map(item => <li>{item}</li>);What does React warn about in the console when keys are missing?
Without keys, React cannot track items properly, leading to inefficient updates and possible UI glitches.
Which option correctly assigns keys to list items in React?
const fruits = ['apple', 'banana', 'cherry']; return fruits.map((fruit, index) => /* fill here */ );
Keys should be stable and unique for each item.
Using the item value as key is stable and unique here. Using index can cause bugs if list order changes. Using random generates new keys each render, breaking React's tracking.
Look at this React component:
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo, i) => (
<li key={i}>{todo.text}</li>
))}
</ul>
);
}When items are added or removed, the UI sometimes shows wrong todo texts. Why?
Think about what happens when list items move but keys stay the same.
Using index as key is unstable if the list changes order or items are added/removed. React reuses DOM nodes incorrectly, causing wrong content to show.
React uses keys during reconciliation to optimize updates. What exactly does React do with keys to improve performance?
Consider how React decides which elements to keep or replace when data changes.
Keys let React identify which elements correspond between renders. This lets React update only changed elements, improving performance and avoiding unnecessary DOM operations.