HomeReact
Chapter 4

04 — Conditional Rendering & Lists

Control what gets rendered and how to efficiently render collections of items.

Conditional Rendering Patterns

PatternWhen to Use
condition && <Comp />Render or nothing
condition ? <A /> : <B />Render one of two
Early returnSkip entire component
Variable assignmentComplex conditions
Object/map lookupMultiple 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} />)}
RuleWhy
Always provide keyReact uses keys to track which items changed
Use stable, unique IDsArray index as key causes bugs on reorder/delete
key stays on the outermost elementInside the .map() callback
Never use Math.random() as keyDifferent 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 />} renders 0 — 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