6) Lists and Keys
Lists and Keys
Lists & Keys in React are used to render collections of data efficiently and correctly update the UI when that data changes.
A list means rendering multiple similar elements from an array.const App = () => { const fruits = ["Apple", "Banana", "Mango"]; return ( <ul> {fruits.map((fruit) => ( <li>{fruit}</li> ))} </ul> ); }React uses JavaScript’s
map()to transform data → UI
Keys are unique identifiers that help React track which items have changed, been added, or removed.keyis a special prop used internally by React{fruits.map((fruit, index) => ( <li key={index}>{fruit}</li> ))}Why are Keys Important
React uses a process called reconciliation (diffing algorithm) to update the DOM efficiently.
Without keys,
i) React may re-render unnecessary elements
ii) UI bugs can occur
With keys,
i) React knows exactly which item changed
ii) Better performance
iii) Correct UI updatesRules for Keys
i) Must be unique among siblings<li key={user.id}>{user.name}</li>ii) Should be stable (not change)
iii) Avoid using index as key (if list changes)Examples
const users = [ { id: 1, name: "Rahul" }, { id: 2, name: "Amit" } ]; <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul>function User({ name }) { return <p>{name}</p>; } {users.map(user => ( <User key={user.id} name={user.name} /> ))}Lists in React are used to render collections using map(), and keys are unique identifiers that help React efficiently update the DOM during reconciliation. Keys should be stable and unique, preferably IDs, and not indexes when the list is dynamic.