Thuta Learning
React
IntermediateWeb DevelopmentIntermediate

Effect Events & Stable Synchronization

ReactLesson 1730 min

What you'll walk away with

  • Explain that every value an Effect reads is a dependency and re-runs it when it changes
  • Move logic that should not cause a reconnect into useEffectEvent so it reads the latest props
  • Follow the rules: call an Effect Event only from inside Effects and never list it as a dependency
  • Tell apart values that should re-run the Effect from values that only need to be read

Explain it simply

Effect Events in plain language

An Effect behaves like a watcher: as soon as a value in its dependency array changes, it tears down what it set up and starts over. That is usually what you want; switching chat rooms really should reconnect. Some values, though, are 'just read it, do not restart for it' values.

useEffectEvent separates that logic from the Effect. The code inside always sees the latest props and state, yet it never becomes a reason for the Effect to re-run. A notification sound toggle, a theme or a locale are typical examples.

Problem → Why → Solution

The problem: muting the chat reconnects it

A ChatRoom component connects to a server for its roomId and plays a sound for each new message unless muted is true. The message handler reads muted, so the linter asks for muted in the dependency array. Once it is there, every press of the mute button drops the connection and reconnects, wasting requests and possibly losing messages that arrive in between.

ChatRoom.jsx
function ChatRoom({ roomId, muted }) {
  const [last, setLast] = useState('');

  useEffect(() => {
    return connect(roomId, (text) => {
      setLast(text);
      if (!muted) playSound(); // reads muted...
    });
  }, [roomId, muted]); // ...so muting disconnects and reconnects

  return <p>{roomId}: {last}</p>;
}

Why not just drop muted from the array?

Removing muted from the array makes the Effect keep the callback from the first render, so it sees a stale muted forever: even after the user unmutes, no sound plays. Silencing the linter only hides that bug. What you actually need is to split the part that is reactive for the connection from the part that merely reads the latest setting when a message arrives.

Core concept: reactive and non-reactive logic

Every prop, state variable and value declared in the component body is reactive: it can change on a new render. When an Effect reads a reactive value, React requires it as a dependency so the Effect never holds on to an old copy, and every change runs the cleanup and then the setup again. Event handlers are different: they run because of a specific interaction, read the latest values at that moment, and never re-run just because a value changed.

An Effect Event is a kind of event handler you can use from inside an Effect. After const onMessage = useEffectEvent((text) => { ... }), every call to onMessage sees the props and state of the latest render, here muted. onMessage itself is not a reactive value, so it does not go in the dependency array, and recent versions of eslint-plugin-react-hooks know not to ask for it. The Effect now depends only on [roomId], and pressing mute no longer touches the connection.

In the chat example, think of the split like this: roomId decides where to connect, so it stays in the Effect, while muted only decides how to react when a message arrives, so it moves into the Effect Event. If one value is needed by both parts, read it in the Effect and pass it to the Effect Event as an argument.

LogicWhere it goes
Must reconnect when it changes (roomId, url)In the Effect, as a dependency
Only read the latest value (muted, theme, locale)Inside useEffectEvent
Runs because of a click or typingA regular event handler

A version note: useEffectEvent is part of stable React starting with React 19.2; before that it existed only in experimental builds, under the name experimental_useEffectEvent. Check the react version in your project's package.json, because importing it on an older version fails with a 'not a function' error.

The Effect connects; the Effect Event reads
  1. Reactive value changes: Effect re-runs
  2. The Effect calls the Effect Event
  3. Effect Event reads the latest props
  4. Its values never trigger a reconnect

Ask: should a change in this value restart the synchronization? If yes, it is a dependency; if no, read it in an Effect Event.

General pattern

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

const onSomething = useEffectEvent((payload) => {
  // reads the latest props/state; NOT a reason to re-run
});

useEffect(() => {
  const handle = setUp(reactiveValue, (payload) => onSomething(payload));
  return () => tearDown(handle);
}, [reactiveValue]); // the Effect Event is not listed

Put the non-reactive logic in useEffectEvent, call it only from the Effect or a callback the Effect set up, and keep only the values that should restart synchronization in the dependency array.

Worked example: a clock that ignores locale changes for its timer

The clock shows the time every second, formatted for the locale prop. When the locale changes, the next tick should use the new format, but there is no reason to destroy the interval and start a new one. So the formatting goes into an Effect Event, and the Effect runs once on mount with [].

jsx
import { useEffect, useEffectEvent, useState } from 'react';

export default function Clock({ locale }) {
  const [time, setTime] = useState('');
  const updateClock = useEffectEvent(() => {
    setTime(new Date().toLocaleTimeString(locale));
  });
  useEffect(() => {
    updateClock();
    const id = setInterval(updateClock, 1000);
    return () => clearInterval(id);
  }, []);
  return <time>{time}</time>;
}

Code breakdown

  1. Import from reactimport { useEffect, useEffectEvent, useState } from 'react';

    useEffectEvent is imported straight from react, which works in React 19.2 and later.

  2. Non-reactive formattingconst updateClock = useEffectEvent(() => {

    The setTime(new Date().toLocaleTimeString(locale)) inside reads the latest locale whenever it is called. The locale never re-runs the Effect.

  3. Called from the Effectconst id = setInterval(updateClock, 1000);

    The Effect updates once immediately and starts the interval. The interval callback was set up by the Effect, so it may call the Effect Event.

  4. Cleanup and empty arrayreturn () => clearInterval(id);

    With [] the interval is cleared only on unmount. updateClock is not listed: Effect Events are not dependencies.

You should see
The <time> element shows the current time (for example 11:03:04 AM for en-US) and updates every second. Changing the locale prop to de-DE switches to a format such as 11:03:05 from the next tick, without restarting the interval.

Before useEffectEvent, and when not to use it

On older React versions you will meet the 'latest ref' pattern: an effect copies the newest callback into a ref after every render, and the connection callback calls ref.current. It has the same goal, but it is longer and easy to get wrong; useEffectEvent replaces the need to hand-write it.

latest-ref.jsx
// Older pattern, before useEffectEvent was stable
const onMessageRef = useRef(null);
useEffect(() => {
  onMessageRef.current = (text) => {
    if (!muted) playSound(text);
  };
});

useEffect(() => {
  return connect(roomId, (text) => onMessageRef.current(text));
}, [roomId]);

Not a way to hide dependencies

If you read roomId inside an Effect Event and give the Effect [], the linter goes quiet, but switching rooms leaves you connected to the old one. Values whose change must restart the connection stay in the Effect as dependencies.

In real projects

Effect Events in real projects

Effect Events show up wherever an app stays connected to an external system and reacts to that system's events using its current settings. In each example below, one value drives the connection and a different value only shapes the reaction.

  • Chat and notifications: the WebSocket connection depends on roomId, while whether to play a sound or show a desktop notification depends on the user's setting.
  • Analytics: log a page view only when the URL changes, and include the latest value such as the cart item count; a cart change must not log a new page view.
  • Map and chart widgets: create the library instance once on mount, and read the latest filter state when a marker click event arrives.
  • Polling and timers: the interval starts once, and each tick reads the latest locale, currency or user preference.

Common mistakes

Common mistakes with Effect Events

Calling it from an event handler or during render

An Effect Event is meant to be called from inside an Effect, not from onClick or while computing JSX. Regular event handlers already see the latest values, so they do not need useEffectEvent at all, and the linter flags this misuse.

Passing it to a child component or another hook

Handing an Effect Event down as a prop, as in <Map onReady={onReady} />, or as an argument to a custom hook breaks its rules. Keep it next to the Effect in the component that declared it, and give children ordinary callbacks.

Hiding a value that should restart the Effect

Moving a value such as roomId into an Effect Event just to silence a dependency warning makes the warning disappear, but switching rooms leaves the app connected to the old room. Decide by asking whether a change in that value should restart the connection.

Mini challenge

Mini challenge: a chat that stays connected when muted

Fix the ChatRoom from the problem section with useEffectEvent. Using a fake connect() function, it must reconnect only when roomId changes, never when muted changes, yet each arriving message must respect the latest muted value.

  • connect(roomId, onMessage) logs 'connect <room>' and returns a disconnect function
  • Message handling (setLast plus the ding log) lives in a useEffectEvent
  • The Effect's dependency array is exactly [roomId]
  • When muted is true no 'ding: ...' is logged, but the last message is still shown
ChatRoom.jsx
import { useEffect, useEffectEvent, useState } from 'react';

// A fake chat server: delivers a message every 2 seconds
function connect(roomId, onMessage) {
  // TODO: log "connect <roomId>", start an interval that calls onMessage
  // TODO: return a function that clears it and logs "disconnect <roomId>"
}

export default function ChatRoom({ roomId, muted }) {
  // TODO: state for the last message
  // TODO: an Effect Event that stores the text and logs "ding: <text>" unless muted
  // TODO: an Effect that connects for roomId and calls the Effect Event
  return null; // TODO: "<roomId>: <last message or 'no messages yet'>"
}

Expected: Starting with roomId='general' logs 'connect general' and then 'ding: hello from general' every 2 seconds. Switching muted to true logs no disconnect or connect: the dings stop while messages keep showing. Only changing roomId to 'travel' logs 'disconnect general' and 'connect travel'. (In development, Strict Mode's connect, disconnect, connect on mount is normal.)

Show hint

Writing return connect(roomId, (text) => onMessage(text)); inside the Effect makes the disconnect function from connect the cleanup. Never read muted in the Effect itself, only inside the Effect Event.

Show solution
ChatRoom.jsx
import { useEffect, useEffectEvent, useState } from 'react';

// A fake chat server: delivers a message every 2 seconds
function connect(roomId, onMessage) {
  console.log(`connect ${roomId}`);
  const id = setInterval(() => onMessage(`hello from ${roomId}`), 2000);
  return () => {
    clearInterval(id);
    console.log(`disconnect ${roomId}`);
  };
}

export default function ChatRoom({ roomId, muted }) {
  const [last, setLast] = useState('');

  const onMessage = useEffectEvent((text) => {
    setLast(text);
    if (!muted) console.log(`ding: ${text}`); // latest muted, not a dependency
  });

  useEffect(() => {
    return connect(roomId, (text) => onMessage(text));
  }, [roomId]); // only a room change reconnects

  return <p>{roomId}: {last || 'no messages yet'}</p>;
}

Quick quiz 1 / 3

In the worked example's Clock, the locale prop changes from 'en-US' to 'de-DE'. What happens?

Quick quiz 2 / 3

Where should an Effect Event be called from?

Quick quiz 3 / 3

A developer writes const onConnect = useEffectEvent(() => connect(roomId)); and then useEffect(() => onConnect(), []). What is the problem?

What to remember

  • Every reactive value an Effect reads is a dependency; a change runs cleanup and setup again
  • Logic inside useEffectEvent reads the latest props and state without re-running the Effect
  • Call Effect Events only from Effects; never list them as dependencies or pass them as props
  • Never hide values that must restart synchronization, such as roomId or url, in an Effect Event
  • useEffectEvent is stable from React 19.2, so check your project's react version

useEffectEvent — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.