Components & Props
React Lists and Keys
Rendering a list means mapping an array to an array of JSX elements. Each element needs a key — a string or number that is stable and unique among its siblings — so React can match items between renders when the list changes.
What is Lists and Keys in React?
Rendering a list means mapping an array to an array of JSX elements. Each element needs a key — a string or number that is stable and unique among its siblings — so React can match items between renders when the list changes.
Why Lists and Keys matters
Keys are how React knows an item moved rather than changed. Get them wrong and you see the classic bugs: checkboxes ticking the wrong row, inputs holding the previous row’s text, animations replaying on every keystroke.
Lists and Keys example
function JobList({ jobs }) {
if (jobs.length === 0) return <p>No internships found.</p>;
return (
<ul>
{jobs.map(job => (
<li key={job.id}>
{job.title} — {job.company}
</li>
))}
</ul>
);
}How this works
The key goes on the outermost element returned by map — the li here, not on children inside it. React uses it to pair the previous element with the new one, preserving DOM nodes and component state across reorders.
Why the index is a bad key
// Items: [A, B, C] with keys 0,1,2.
// Delete A -> [B, C] with keys 0,1.
// React thinks item 0 changed from A to B and item 2 was removed,
// so B inherits A's DOM node and any state inside it.
{items.map((item, i) => <Row key={i} item={item} />)} // avoidKey points to remember
- Keys must be unique among siblings, not globally unique.
- Prefer a database id; fall back to a stable composite like `${type}-${slug}`.
- Index keys are acceptable only for a static list that is never reordered, filtered or added to.
- Never use Math.random() as a key — every render produces a new key and remounts everything.
Common mistakes with Lists and Keys
- Putting the key on an inner element instead of the mapped root.
- Using the index in a sortable or filterable list.
- Forgetting keys entirely, which produces a console warning and subtle state bugs.
React Lists and Keys— Interview Questions & FAQs
Why does React need keys?+
To match elements between the previous and next render. Without a stable identity React falls back to position, so inserting or reordering items makes it update the wrong nodes and misplace component state.
Is it ever fine to use the array index as a key?+
Only when the list is static — never reordered, filtered, or added to — and the items have no internal state or form inputs. When in doubt, use a real id.
