Capítulo 53 de 116

Chapter 53: useEffect

Core Idea

useEffect(setup, dependencies?) is the API reference behind the conceptual model built up in Ch 36/38: setup runs after commit, may return a cleanup function, and re-runs whenever a listed dependency changes between renders — this chapter is the precise parameter/timing contract.

Key Concepts

  • Signature: useEffect(setup, dependencies?). setup is the function React runs after the DOM updates; if it returns a function, that's the cleanup, run before the next setup call and on unmount.
  • Three dependency-array forms: omitted → runs after every render (rare, usually a mistake); [] → runs once after initial mount only; [a, b] → runs after mount and after any render where a or b differs from the previous render (compared with Object.is).
  • Timing: Effects run after the browser has painted for most cases (this is why they don't block visual updates) — contrast with useLayoutEffect (Ch 58), which runs synchronously before paint.
  • Caveats worth remembering: setup/cleanup must be synchronous functions (an Effect callback itself can't be async, though it can call async functions inside); in Strict Mode development builds, React runs setup → cleanup → setup once extra on mount specifically to surface missing/incorrect cleanup; if a dependency is an object/function recreated every render, the Effect re-runs every render unless that's addressed (Ch 40).
  • Not for user-triggered logic — reiterating Ch 37/Ch 39's distinction: useEffect is for staying synchronized with something external as long as the component (and its dependency values) are present, not for reacting to one specific interaction.

Code Examples

useEffect(() => {
  document.title = `${unreadCount} unread messages`;
}, [unreadCount]);
  • What it demonstrates: the minimal shape — synchronizing a value (the document title) with a reactive dependency (unreadCount), re-running only when that value changes.

Key Takeaways

  1. An omitted dependency array (running after every render) is almost always a mistake, not a deliberate choice — be explicit.
  2. The cleanup function must undo exactly what setup did, so repeated mount→cleanup→mount cycles (Strict Mode, or genuine remounts) never leak or duplicate a subscription/connection.
  3. This is the API surface for the concepts covered narratively in Ch 36-40 — read those first if the why behind dependencies isn't already clear.

Connects To

  • Ch 36 (Synchronizing with Effects): the conceptual introduction this reference formalizes.
  • Ch 58 (useLayoutEffect): the synchronous, pre-paint variant.
  • Ch 54 (useEffectEvent): extracting non-reactive logic out of an Effect's body.