HomeReact
Chapter 4
04 — Conditional Rendering & Lists
Control what gets rendered and how to efficiently render collections of items.
Conditional Rendering Patterns
| Pattern | When to Use |
|---|---|
condition && <Comp /> | Render or nothing |
condition ? <A /> : <B /> | Render one of two |
| Early return | Skip entire component |
| Variable assignment | Complex conditions |
| Object/map lookup | Multiple variants |
> Gotcha: 0 && <Comp /> renders 0 (a falsy but visible value). Use count > 0 && instead.
List Rendering Rules
{items.map(item => <Card key={item.id} item={item} />)}| Rule | Why |
|---|---|
Always provide key | React uses keys to track which items changed |
| Use stable, unique IDs | Array index as key causes bugs on reorder/delete |
key stays on the outermost element | Inside the .map() callback |
Never use Math.random() as key | Different key every render = remount |
When Index as Key is OK
- Static list that never reorders or filters
- Items have no state of their own
- List is never sorted
Common Pitfalls
{0 && <X />}renders0— use{count > 0 && <X />}- Missing keys causes incorrect DOM reuse and state bugs
- Filtering + map — filter FIRST, then map (not inside map)
File
conditional-lists.tsx— all conditional patterns, list rendering, key prop, filtering, sorting, nested lists