Capítulo 21 de 116

Chapter 21: State: A Component's Memory

Core Idea

A regular local variable doesn't survive a re-render and doesn't cause one when changed — useState solves both problems, giving a component a value React remembers across renders and a setter that schedules a new render with the updated value.

Key Concepts

  • Why a plain variable fails: it's reset to its initial value on every call (component functions re-run from scratch), and mutating it doesn't tell React to re-render at all — the screen simply never updates.
  • const [index, setIndex] = useState(0): useState's only argument is the initial value; it returns a [value, setter] pair. The [something, setSomething] naming is convention, not required.
  • Mental model of the update cycle: initial render → useState(0) returns [0, setIndex], React remembers 0. Event fires setIndex(1) → React remembers 1 and schedules a re-render. Next render → useState(0) is called again (same argument!) but React returns [1, setIndex] because it now remembers 1, not the literal argument passed.
  • Multiple state variables: a component can call useState as many times as it needs — each call is independently tracked (order matters, hence the Rules of Hooks in Ch 116).
  • State is per-component-instance, isolated and private. Rendering the same component twice on screen (<Gallery /><Gallery />) gives each instance its own completely independent state — updating one never affects the other. This is the same isolation seen with the two-counter example in Ch 1, now explained mechanically.

Code Examples

const [index, setIndex] = useState(0);

function handleNextClick() {
  setIndex(index + 1);
}
  • What it demonstrates: the canonical useState shape — an initial value in, a [value, setter] pair out, and a setter call that both updates the remembered value and schedules a re-render.

Key Takeaways

  1. useState's argument is only ever read on the very first render — treat it purely as "initial value," not as something React re-applies on every call.
  2. Two instances of the same component on screen never share state, even though they run the identical component function — state belongs to the instance (its position in the tree), not the function definition.
  3. If a component needs several independent pieces of remembered data, call useState multiple times rather than cramming everything into one state object, unless the values are tightly related and always change together.

Connects To

  • Ch 22 (Render and Commit): what a setIndex call actually schedules.
  • Ch 23 (State as a Snapshot): why index inside a handler doesn't update mid-function even after calling the setter.
  • Ch 116 (Rules of Hooks): why Hook call order must stay stable across renders.