Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 132 ยท Hooks

useEffectEvent

Learn useEffectEvent in React 19.2 and later - split event-like logic out of effects, read the latest props and state without re-running, avoid stale closures, and know the rules and limits.

Effects have a built-in tension. The dependency rule says an effect must list every reactive value it reads, so that it stays in sync. But sometimes an effect reads a value only to use it at one particular moment (to show a message, to log something, to call a callback) and you do not want a change in that value to restart the whole effect. Think of a chat connection that should reconnect when the room changes but not when the user toggles dark mode, even though the "connected" message is coloured by the theme.

Before React 19.2 you had two bad options: list the value and restart needlessly, or hide it (suppress the lint rule, or stash it in a ref) and risk stale data. useEffectEvent is the third option. It lets you declare "this piece of logic is an event that happens to be fired from an effect": it always sees the latest props and state, and it is not a dependency. This lesson shows the problem, the fix, and, just as important, the limits.

The problem: a dependency that causes needless restarts

Here is a small chat room. Connecting is a real side effect (we simulate it with logs), and when it succeeds the app shows a message styled according to the current theme.

Theme in the dependency array reconnects the room

After the initial connecting to general..., connected to general and the toast, press "Theme: light". The console shows disconnected from general and connecting to general... all over again: the connection was dropped and rebuilt only because a colour changed. In a real chat that means lost messages, extra network traffic and a visible flicker.

The linter is right that theme is read, so removing it from the array would be a lie (the toast would later use a stale theme). The honest question is whether the toast should count as part of the synchronization at all. It should not: connecting to a room is the synchronization; the toast is an event that happens when the connection completes, and it should use whatever theme is current at that moment.

The fix: useEffectEvent

useEffectEvent wraps a function so that it is not reactive. You call it from inside your effect; the function always sees the latest props and state; and React does not treat it as a dependency.

JSX
import { useEffect, useEffectEvent } from 'react';

const onConnected = useEffectEvent(() => {
  showToast(theme);          // reads the latest theme
});

useEffect(() => {
  const disconnect = connect(roomId);
  onConnected();             // fired from the effect, but not a dependency
  return disconnect;
}, [roomId]);                // only roomId re-synchronizes

Here it is running in the editor:

The theme no longer restarts the connection

Press "Theme: light" now and the console stays quiet: no disconnect, no reconnect. Press "Switch room" and you get the pair disconnected from general, connecting to music... as before. The effect still reacts to what it should react to, the room, and nothing else.

To see the "always latest" part, press "Switch room" and then "Theme" within about 40 ms (or imagine a slower connection). The effect started with the old theme, yet the toast reports the new one, for example toast (light theme): welcome to general after the theme was flipped back. That is the point: the event function is re-created every render, and the effect always calls the newest version.

Mental model: reactive code versus event-like code

Inside a component, there are two kinds of logic:

Reactive logic Event-like logic
Lives in The component body, effect setup Event handlers, useEffectEvent functions
When it runs Because something it reads changed Because something specific happened
Reads Latest values at the moment of rendering Latest values at the moment it is called
Should be a dependency? Yes No

A click handler is naturally event-like: it runs when the user clicks and reads the current state. An effect is reactive: it re-synchronizes whenever its inputs change. useEffectEvent lets you pull a piece of event-like logic that is triggered from inside an effect (a notification, a log line, a callback to a parent) out of the reactive part, so that part is not forced to re-run.

More examples

A callback prop that is created inline

Parents often pass fresh arrow functions: <Timer onTick={() => setLog(...)} />. An effect that lists onTick would restart its timer on every parent render. An effect event solves it cleanly.

A timer that ignores callback identity

The console shows interval started exactly once, even though the parent re-renders on every tick and on every keystroke, each time handing Ticker a brand-new onTick. Without useEffectEvent the effect would have [onTick] as its dependency and the log would fill with interval cleared and interval started pairs.

Logging or analytics with extra context

A page-view event should fire when the URL changes, and include the cart size at that moment, but a change in the cart must not log another page view.

JSX
function Page({ url, cartItems }) {
  const logVisit = useEffectEvent((visitedUrl) => {
    analytics.track('visit', { url: visitedUrl, items: cartItems.length });
  });

  useEffect(() => {
    logVisit(url);
  }, [url]);
}

(analytics is a stand-in for a third-party library, so this snippet is read-only.)

What it is not for

useEffectEvent is not a general "ignore dependencies" switch. Misusing it recreates the stale-value bugs the dependency rule exists to prevent.

  1. Don't use it to silence the linter. If a value should cause re-synchronization (the roomId above), it must stay a dependency. Ask: "if this value changes, should the outside world be updated?" If yes, the code is reactive; if the value is only read when something happens, it is event-like.
  2. Only call it from inside effects (or from other effect events). React enforces part of this at runtime:
Calling an effect event during render (fails on purpose)

The page stays empty and the console shows an uncaught error: A function wrapped in useEffectEvent can't be called during rendering. Rendering has to be pure and reactive, so use a plain function in render. (Also don't call effect events in event handlers; plain functions are right there.)

  1. Don't pass an effect event to other components or hooks, and do not put it in a dependency array. It is only valid to call it locally. Passing it down would let a child call it during its render or at arbitrary times, when the "latest values" guarantee no longer makes sense. The lint rule from eslint-plugin-react-hooks flags this, and also does not demand effect events in dependency lists.
  2. Don't use it to avoid fixing the design. Many effects with awkward dependencies should instead move logic into event handlers, derive values during render, or use a functional update (Effect Dependencies, You Might Not Need an Effect). Reach for useEffectEvent after those.
  3. It is not a memoization hook. The function identity changes every render and you must not rely on it (that is why it is not allowed in dependency arrays). It is not a replacement for useCallback.

Before and after: a quick comparison

Technique Reads latest value? Restarts effect? Downsides
Put the value in dependencies Yes Yes, on every change Needless teardown/setup
Remove it and suppress the linter No (stale) No Stale-closure bugs
Store it in a ref, update in another effect Yes No Boilerplate, easy to get wrong, no lint support
useEffectEvent Yes No Only callable from effects; extra concept

Status and availability

useEffectEvent shipped as stable in React 19.2 and is available in the React 19.3 build that this tutorial's editor loads (import { useEffectEvent } from 'react' worked in every example above). If you are on an older React, use the ref pattern from useRef instead, or upgrade. Make sure your lint setup is recent: older versions of eslint-plugin-react-hooks do not know about effect events and complain about, or fail to check, them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main purpose of useEffectEvent?

    useEffectEvent extracts event-like logic from an effect: it always sees the latest values, and the effect does not re-run when those values change.
  2. 2. A chat effect connects to roomId and shows a toast in the current theme once connected. Which dependency array is correct when the toast uses an effect event?

    Only roomId should cause a reconnect. The theme is read inside the effect event, which is not a dependency.
  3. 3. What happens if you call an effect event during rendering?

    Calling it in render throws, because render must be pure and effect events exist for code that runs after rendering.
  4. 4. Which is a misuse of useEffectEvent?

    roomId is what the effect synchronizes with: changing it must reconnect. Hiding it in an effect event makes the connection go stale.
  5. 5. Should you pass an effect event to a child component as a prop?

    An effect event is only valid where React can guarantee it runs after rendering, in the effect that declared it. Passing it elsewhere breaks that guarantee.

Summary

  • useEffectEvent(fn) returns a function that always runs the latest fn but is not a dependency, so changes to the values it reads don't re-run the effect.
  • Use it for event-like logic fired from inside an effect: notifications, logging, calling a parent callback.
  • Keep genuinely reactive values (the things the effect synchronizes with) in the dependency array.
  • Only call effect events from effects or other effect events: not during render, not as props, not in dependency lists.
  • Try simpler fixes first (handlers, derived values, functional updates), then reach for useEffectEvent.
  • It is stable from React 19.2 and runs in the editor on 19.3, with no extra setup.

Next: useMemo and useCallback