Sikau

React patterns at scale · Day 3 · about 35 min

Where state should live

Container and presentational parts, colocation and lifting.

Every keystroke re-renders the menu

A café order screen keeps all its state at the top: the note for the kitchen, the selected dish, the filter text. It works — until the menu has three hundred items and typing a note feels sticky, because every keystroke re-renders the whole page. Nothing is wrong with React; the state is just in the wrong place.

Before reaching for memo or a state library, ask the cheapest question in React performance: who actually needs this state? Kent C. Dodds calls the answer state colocation, and the React docs pair it with its opposite move, lifting state up. Together they decide most of an app's structure.

Containers and presentational components

The Learning Patterns book describes a classic split. A presentational component cares about *how* data looks: it receives everything through props, reports events through callbacks, and usually holds no state except for UI details. A container component cares about *what* data is shown: it fetches or holds the state and hands it down.

function MenuList({ dishes, selectedId, onSelect }) {
  return (
    <ul>
      {dishes.map((d) => (
        <li key={d.id}>
          <button aria-pressed={d.id === selectedId} onClick={() => onSelect(d.id)}>
            {d.name}
          </button>
        </li>
      ))}
    </ul>
  );
}

The book also notes that hooks made the strict split less necessary: a custom hook such as useDishes() can hold the fetching logic, and the component that renders can call it directly, with no wrapper container. The idea that survives is the separation itself — logic in one place, display in another — not a rule that every component must be one or the other.

The rest of this lesson

  • Down as far as possible, up only as far as neededexplain
  • Who re-renders?predict
  • Where does it go?match
  • Lifting state uporder
  • Move the statewrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 10 lessons of React patterns at scale