Capítulo 54 de 116
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.
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.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.const onVisit = useEffectEvent((url) => {
logAnalytics(url, numberOfItems); // always latest numberOfItems
});
useEffect(() => {
onVisit(url);
}, [url]); // numberOfItems intentionally not listed — read via the Effect Event
numberOfItems stays current inside onVisit without forcing the outer Effect to re-run whenever it changes — only url drives re-synchronization.