Code in an effect is reactive: every prop, state or render-scope value it reads is a dependency, and a change re-runs the effect. Code in an event handler isn't: it runs when the user acts and reads whatever the latest values are.
Some effects contain a bit of event-like logic. A chat room connects in an effect keyed on roomId; when the connection opens, it shows a notification in the current theme. The connection should follow roomId, but not theme:
- List
themeand every theme switch disconnects and reconnects. - Leave it out and
react-hooks/exhaustive-depswarns, and the notification uses the theme from when the effect ran: a stale closure.
useEffectEvent splits the two. Wrap the notification in const onConnected = useEffectEvent(() => showNotification('Connected!', theme)) and call onConnected() from the effect. When called, it runs the callback from the latest committed render, so it sees the current theme, and it is not a dependency. The effect lists only roomId. It's stable since React 19.2.
The rules, enforced by eslint-plugin-react-hooks:
- Call it only from inside
useEffect,useLayoutEffect,useInsertionEffect, or another Effect Event in the same component. Not from handlers, not during render (that throws), not passed to children or other hooks. - Never list it as a dependency. Its identity changes on every render, deliberately, so misuse shows up as an effect re-running each render.
- Use it only for logic that really is an event fired by the effect. Wrapping code just to drop a dependency the effect should react to hides bugs: a visit logged without
urlin its dependencies misses page changes.
Before it existed, most code disabled the lint rule and left the value out, as the React 19.2 announcement notes; the linter then stopped checking that effect.