Capítulo 54 de 116

Chapter 54: useEffectEvent

Core Idea

useEffectEvent(callback) is the API reference for the pattern introduced in Ch 39: it produces a stable function, callable only from inside an Effect, whose body always sees the latest props/state when it actually runs, without those values needing to be Effect dependencies.

Key Concepts

  • Signature: const onSomething = useEffectEvent(callback) — returns a function with a stable identity across renders (like useCallback with an empty dependency array), but unlike useCallback, its body isn't a stale closure over old values; each call reads the current render's values.
  • Only call it from inside an Effect (or another Effect Event) — it's explicitly not meant to be passed as a prop, used as a JSX event handler directly, or called from outside the Effect lifecycle it's meant to serve.
  • Never add an Effect Event to a dependency array. Its whole purpose is to be the non-reactive escape hatch — including it as a dependency would defeat that (and the linter treats it accordingly, not requiring it).
  • Solves the "want the latest value, but shouldn't cause a re-run" tension that a plain closure inside useEffect can't — a normal function defined in the component body and read inside an Effect is either stale (if not a dependency) or over-triggers the Effect (if added as one); an Effect Event is neither.

Code Examples

const onVisit = useEffectEvent((url) => {
  logAnalytics(url, numberOfItems); // always latest numberOfItems
});

useEffect(() => {
  onVisit(url);
}, [url]); // numberOfItems intentionally not listed — read via the Effect Event
  • What it demonstrates: numberOfItems stays current inside onVisit without forcing the outer Effect to re-run whenever it changes — only url drives re-synchronization.

Key Takeaways

  1. Effect Events exist for exactly one situation: a value read inside an Effect that must be current but must not be reactive.
  2. Calling one outside of an Effect context is a misuse of the API — it's not a general "stable callback" utility.
  3. Never list an Effect Event itself in a dependency array — its stability is guaranteed by construction.

Connects To

  • Ch 39 (Separating Events from Effects): the conceptual walkthrough this reference formalizes.
  • Ch 53 (useEffect): the Effect this Hook is always called from within.