Capítulo 70 de 116

Chapter 70: Suspense

Core Idea

<Suspense fallback={...}> shows a fallback UI for its children while any of them "suspend" (aren't yet ready to render — typically because they're waiting on data or code to load), then automatically swaps to the real content once everything inside is ready.

Key Concepts

  • Basic shape: <Suspense fallback={<Spinner />}><SomeComponentThatMightSuspend /></Suspense> — while a descendant suspends, the entire subtree inside that Suspense boundary is replaced by fallback; once every suspended part resolves, the boundary reveals the real content all at once.
  • What causes suspending: components using data-fetching integrated with Suspense (e.g. via use, or a framework's data layer), or lazy-loaded components (lazy, Ch 87) whose code chunk hasn't finished downloading yet.
  • Nesting reveals content progressively: nested Suspense boundaries let different parts of a page reveal independently as their own data becomes ready, rather than the whole page waiting on the single slowest piece — a shallow boundary can show a shell immediately while deeper boundaries stream in their content.
  • Not itself a data-fetching mechanismSuspense is the coordination boundary; the actual fetching/loading integration comes from a framework or a Suspense-compatible library (or the use Hook reading a promise), not from Suspense itself.
  • Server Components and streaming (Ch 110) pair naturally with Suspense — a server can start streaming the shell immediately and stream in suspended sections as their data resolves, without waiting for the whole page.

Code Examples

<Suspense fallback={<h2>Loading comments...</h2>}>
  <Comments />
</Suspense>
  • What it demonstrates: Comments suspending while it loads swaps in the fallback heading; once ready, React reveals Comments in place.

Key Takeaways

  1. Suspense coordinates when to show a fallback vs. real content — it doesn't fetch anything itself.
  2. Nest boundaries deliberately to control granularity — one boundary per "should this region load independently" concern, not one giant boundary around everything.
  3. Pairs directly with lazy (code-splitting) and Suspense-integrated data fetching (use, framework data layers, RSC streaming) as the piece that actually triggers suspension.

Connects To

  • Ch 87 (lazy): the code-splitting use case that suspends a Suspense boundary.
  • Ch 91 (use): reading a promise inside render in a way that integrates with Suspense.
  • Ch 110 (Server Components): streaming server-rendered content into Suspense boundaries.