Sub topic 2
Choosing Good Keys: IDs, Not Indexes
Assume you know JavaScript arrays, map, filter, arrow functions, React components, props, JSX, and useState.
Choose Stable Keys
A key identifies a list item among its siblings. React uses it to match the previous item with the next item when data changes.
Use a stable, unique ID from the data:
function PeopleList({ people }) {
return (
<ul>
{people.map(person => (
<li key={person.id}>{person.name}</li>
))}
</ul>
);
}An array index is only safe when the list never changes order and items are never inserted or removed. Otherwise, React may reuse the wrong DOM or component state for an item.
Extract List Item Components
Move item markup into a component when it becomes complex. Keep the key where map creates the list:
function PersonRow({ person }) {
return <li>{person.name}</li>;
}
function PeopleList({ people }) {
return (
<ul>
{people.map(person => (
<PersonRow key={person.id} person={person} />
))}
</ul>
);
}Keyed Fragments
When one item produces multiple sibling elements, put the key on an explicit Fragment. The short <>...</> syntax cannot receive a key.
import { Fragment } from 'react';
function Glossary({ entries }) {
return (
<dl>
{entries.map(entry => (
<Fragment key={entry.id}>
<dt>{entry.term}</dt>
<dd>{entry.definition}</dd>
</Fragment>
))}
</dl>
);
}Filter and Sort Without Mutation
filter returns a new array. sort mutates its array, so copy before sorting:
const visible = people
.filter(person => person.active)
.toSorted((a, b) => a.name.localeCompare(b.name));If toSorted is unavailable, use [...people].sort(...).
Choose Conditional Forms
Use an if and early return when a whole component has an alternate state:
function Results({ items }) {
if (items.length === 0) {
return <p>No results.</p>;
}
return <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>;
}Use a ternary when choosing between two JSX outputs:
return items.length > 0
? <ResultsList items={items} />
: <p>No results.</p>;Exercise
Why is key={index} risky when items can be removed or reordered?
Show answer
The index can then refer to a different item, so React may preserve the wrong item's DOM or component state.