In React, the key prop uniquely identifies elements in a list. It helps React efficiently update, insert, or remove items during re-renders. Correct key usage improves performance and prevents unexpected UI behavior.
When rendering lists, React compares old and new virtual DOM trees. Keys allow React to match elements correctly and reuse DOM nodes when possible. Without keys, React may unnecessarily re-render items.
// Rendering a list without keys (inefficient)
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li>{todo.text}</li>
))}
</ul>
);
}
// Rendering a list with stable keys (recommended)
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
key changes, React unmounts and remounts the elementkey stays the same, React updates only changed props
// Changing the key forces input reset
function InputBox({ id }) {
return <input key={id} placeholder="Type here..." />;
}
When the id value changes, React treats the input as a new element. The previous input is unmounted and its state is discarded.
// Bad vs good key usage
{todos.map((todo, index) => (
<li key={index}>{todo.text}</li>
))}
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
Goal: Understand how correct key usage improves rendering efficiency and prevents unnecessary re-renders.