
ReactJS
Keys help React identify which items have changed, been added, or been removed.
// ❌ Without keys - React re-renders all items
function List() {
const [items, setItems] = React.useState(["A", "B", "C"]);
return (
<ul>
{items.map((item, i) => (
<li key={i}>{item}</li> // Using index as key (bad)
))}
</ul>
);
}
// ✅ With stable keys - React knows which item changed
function List() {
const [items, setItems] = React.useState([
{ id: 1, text: "A" },
{ id: 2, text: "B" },
{ id: 3, text: "C" }
]);
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.text}</li> // Stable key
))}
</ul>
);
}React reconciles (compares) old and new lists:
Good keys are:
function TextInputList() {
const [inputs, setInputs] = React.useState([
{ id: 1, value: "" },
{ id: 2, value: "" }
]);
const handleChange = (id, value) => {
setInputs(inputs.map(input =>
input.id === id ? { ...input, value } : input
));
};
return (
<div>
{inputs.map(input => (
<input
key={input.id}
value={input.value}
onChange={(e) => handleChange(input.id, e.target.value)}
/>
))}
</div>
);
}| Scenario | Performance |
|---|---|
| Adding to end with stable keys | Good - React adds one element |
| Inserting at start with index keys | Bad - React updates all positions |
| Filtering with ID keys | Good - React removes only deleted items |
| Reordering with ID keys | Good - React re-arranges existing elements |
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward