The key Prop
The key Prop
The key prop is a special React attribute that you must provide on every element inside a list (the direct child of a .map() call). It is a unique string or number that React uses internally to identify which items in a list have changed, been added, or been removed between renders. Keys help React perform efficient DOM reconciliation by tracking list items precisely.
Without keys, React would have to re-render the entire list from scratch every time anything changes. With keys, React can pinpoint exactly which items changed and only update those specific DOM nodes making updates dramatically faster.
Correct Key Usage
JSX
const users = [ { id: 'u-001', name: 'Rahat Hussain' }, { id: 'u-002', name: 'Murtaza Ali' }, { id: 'u-003', name: 'Gulzar Ahmed' }, ]; function UserList() { return ( <ul> {users.map((user) => ( {/* BEST: Unique ID from data */} <li key={user.id}>{user.name}</li> ))} </ul> ); } // Also valid: unique string from data courses.map((c) => <Card key={c.slug} data={c} />); // Crypto UUID for dynamically generated items import { v4 as uuidv4 } from 'uuid'; items.map((item) => <Item key={item.id || uuidv4()} />);
Where Exactly Does the key Go?
The key must be placed on the outermost element returned from the map callback, even when that element is a Fragment. Keys must be unique among siblings within the same list, not globally across the whole app.
JSX
import { Fragment } from 'react'; function ProductRows({ products }) { return ( <table> <tbody> {products.map((p) => ( {/* key on Fragment — when returning multiple sibling elements */} <Fragment key={p.id}> <tr> <td>{p.name}</td> <td>{p.price}</td> </tr> <tr> <td colSpan={2}>{p.description}</td> </tr> </Fragment> ))} </tbody> </table> ); } // Note: <React.Fragment key={...}> works, but <></> shorthand // does NOT accept the key prop — use <Fragment> explicitly
