Consider a React component rendering a list of items. Why is it important to assign a unique key prop to each list item?
function ItemList({ items }) { return ( <ul> {items.map(item => <li key={item.id}>{item.name}</li>)} </ul> ); }
Think about how React updates the UI when data changes.
Keys let React track each element in a list so it can update only the changed items efficiently. Without keys, React may re-render all items unnecessarily.
Given this React code, what will be the output behavior when the list updates?
function FruitList() { const [fruits, setFruits] = React.useState(['apple', 'banana', 'cherry']); React.useEffect(() => { setTimeout(() => { setFruits(['banana', 'apple', 'cherry']); }, 1000); }, []); return ( <ul> {fruits.map(fruit => <li key={fruit}>{fruit}</li>)} </ul> ); }
What happens if React cannot distinguish list items by keys?
Using the same key for all items confuses React's diffing algorithm, leading to incorrect updates or UI bugs.
Which option correctly assigns keys in this React list rendering?
const users = [{id: 1, name: 'Anna'}, {id: 2, name: 'Ben'}, {id: 3, name: 'Cara'}]; function UserList() { return ( <ul> {users.map(user => ( <li key={/* key here */}>{user.name}</li> ))} </ul> ); }
Keys should be stable and unique for each item.
Using user.id is stable and unique. Using index or random values can cause bugs during re-rendering.
Why does React show this warning: "Each child in a list should have a unique 'key' prop."?
function TodoList({ todos }) { return ( <ul> {todos.map(todo => <li>{todo.text}</li>)} </ul> ); }
Check the list items inside the map function.
React requires each list child to have a unique key prop to track elements properly.
In React, why is it generally discouraged to use the array index as the key prop when rendering dynamic lists?
Think about what happens when list items move or change.
Using indexes as keys can confuse React when items reorder or change, leading to bugs like wrong state or unnecessary re-renders.