Keys help React identify which items in a list have changed, been added, been removed or been reordered. They let React match elements between renders correctly during reconciliation. Basic usage function TodoList({ todos }: { todos: Todo[] }) { return ( <ul> {todos.map(todo => ( <li key={todo.id}>{todo.text}</li> ))} </ul> ); } Without keys, React warns ("Each child in a list should have a unique key prop") and falls back to matching children by position. Why keys matter 1. Correct updates When a list changes, React compares the old and new children by key. Items with the same key are treated as the same element: React updates them instead of destroying and recreating them. 2. Preserving component state State, focus and uncontrolled input values belong to a component instance. If keys are wrong, state can attach to the wrong item. Classic bug with array indexes as keys {items.map((item, index) => <li key={index}><input defaultValue={item.name} /></li>)} If you insert a new item at the top, every index shifts. React thinks item 0 is still the same element, so the text typed into the first input now appears next to the wrong item, and inputs show stale values. With key={item.id}, React knows the new item is new and keeps existing inputs attached to their items. 3. Performance Stable keys let React move existing DOM nodes when items are reordered instead of updating every node's content or recreating nodes. Rules for good keys - Unique among siblings (they only need to be unique within the same list, not globally). - Stable across renders: the same item must always get the same key. - Use IDs from your data (database IDs, UUIDs assigned when the item is created). - Do not generate keys during render with Math.random() or crypto.randomUUID() — a new key every render forces React to remount every item, losing state and hurting performance. - Array index is acceptable only when the list is static: never reordered, filtered or inserted into, and items have no state. Keys on fragments <React.Fragment key={item.id}><dt>{item.term}</dt><dd>{item.description}</dd></React.Fragment> Keys are not passed as props The key prop is used by React itself; the child component cannot read props.key. Pass the ID separately if needed (id={item.id}). Using keys to reset a component deliberately Changing a component's key tells React to discard it and create a new instance: <ProfileForm key={selectedUserId} userId={selectedUserId} /> When the selected user changes, the form resets its internal state — a clean pattern instead of syncing state with effects. Interview summary: "Keys let React's reconciliation match list items between renders. Stable, unique keys like database IDs keep updates efficient and ensure state stays with the right item; using indexes or random values causes bugs and unnecessary remounts."
Ravindra Wadile · · 0 likes