Capítulo 57 de 116

Chapter 57: useInsertionEffect

Core Idea

useInsertionEffect(setup) runs before any DOM mutations from the current commit are applied — a highly specialized Hook meant almost exclusively for CSS-in-JS library authors who need to inject <style> tags before layout is read by anything else, not for application code.

Key Concepts

  • Timing relative to the other Effect Hooks: useInsertionEffect fires before useLayoutEffect, which fires before useEffect — this Hook exists specifically to guarantee styles are in the DOM before layout effects run and could read stale/missing styles.
  • No access to refs: unlike useLayoutEffect, DOM refs aren't yet attached when useInsertionEffect runs, since it fires even earlier in the commit sequence — it's only appropriate for injecting global style rules, not for reading/measuring specific elements.
  • Narrow intended audience: the docs are explicit that this Hook is for CSS-in-JS library authors solving the "inject styles before layout reads them" problem — application code essentially never needs it directly.
  • Signature mirrors useEffect: useInsertionEffect(setup), with setup optionally returning cleanup, but without a dependency-array-driven "skip if unchanged" nuance being the primary concern the way it is for useEffect.

Key Takeaways

  1. If you're not authoring a CSS-in-JS styling library, you almost certainly want useLayoutEffect or useEffect instead, not this Hook.
  2. Its entire reason to exist is commit-phase ordering relative to layout — memorize the order (useInsertionEffectuseLayoutEffectuseEffect) rather than the mechanics.
  3. Refs aren't available yet at this point in the commit — don't try to read layout or DOM node references here.

Connects To

  • Ch 58 (useLayoutEffect): the next Effect Hook in commit-phase order, and the one application code should reach for instead.
  • Ch 53 (useEffect): the general-purpose Effect Hook for anything not specifically about pre-layout style injection.