Effect events

Topic 4 of 5 in Refs & effects6 min readIntermediateFree course

Overview

Sometimes an effect needs to read a value without reacting to it. A chat room should reconnect when the room changes, but not when the theme changes — even though the “Connected!” notification uses the theme. Before React 19.2, there was no clean way to express this. Now there’s useEffectEvent.

The problem

JSX
function ChatRoom({ roomId, theme }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.on('connected', () => {
      showNotification('Connected!', theme);
    });
    connection.connect();
    return () => connection.disconnect();
  }, [roomId, theme]); // theme must be listed — it's used inside
}

The linter (correctly) insists that theme is a dependency. But that means switching from light to dark mode disconnects and reconnects the chat. Leaving theme out of the array would fix the reconnecting — but then the notification shows the old theme, because the effect’s closure captured it. And silencing the linter hides real bugs.

The issue is that this effect mixes two kinds of logic:

  • reactive logic — connecting to roomId — should re-run when roomId changes,
  • non-reactive logic — showing a notification with the current theme — should use the latest value but never cause a reconnect.

useEffectEvent

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

function ChatRoom({ roomId, theme }) {
  const onConnected = useEffectEvent(() => {
    showNotification('Connected!', theme);
  });

  useEffect(() => {
    const connection = createConnection(roomId);
    connection.on('connected', () => {
      onConnected();
    });
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]); // ✓ theme isn't used by the effect directly any more
}

useEffectEvent wraps the notification code that reads the latest theme. The effect creates a connection for roomId, calls onConnected when connected, and disconnects in cleanup; its dependency array contains only roomId, and theme is not a dependency. roomId changes cause a reconnect (reactive); theme changes don’t (non-reactive).

onConnected is an Effect Event. It behaves like an event handler: it runs in response to something (the connection firing connected) rather than because a value changed, and when it runs it sees the latest props and state. It isn’t reactive, so it doesn’t belong in the dependency array — and the React Hooks lint rule knows that.

A common use: logging and analytics

JSX
function Page({ url }) {
  const { items } = useCart();

  const onVisit = useEffectEvent((visitedUrl) => {
    logVisit(visitedUrl, items.length);
  });

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

You want to log a visit when the URL changes, including the cart size at that moment — but not log again when the cart changes. Notice that url is passed as an argument. That makes it explicit that a different url is a different “event” from the user’s perspective, while items is just read.

Intervals with the latest values

Effect Events are also a clean fix for intervals and subscriptions that need fresh state:

JSX
function Timer({ step }) {
  const [count, setCount] = useState(0);

  const onTick = useEffectEvent(() => {
    setCount((c) => c + step); // always uses the latest step
  });

  useEffect(() => {
    const id = setInterval(() => onTick(), 1000);
    return () => clearInterval(id);
  }, []); // the interval is created once and never restarted
}

Without the Effect Event, you’d either restart the interval every time step changes or read a stale step.

Rules for Effect Events

  • Only call them from inside effects (including callbacks set up in effects, like listeners and timers). Calling one during render throws “A function wrapped in useEffectEvent can’t be called during rendering”, and the lint rule flags calls from anywhere else, such as regular event handlers.
  • Don’t pass them to other components or hooks. Declare them next to the effect that uses them.
  • Never add them to a dependency array. They’re deliberately not reactive.
  • Don’t use them to hide dependencies. If logic should re-run when a value changes, that value belongs in the effect. Effect Events are for code that genuinely represents an event.

Before useEffectEvent

You’ll see older code solve this with a ref that’s updated on every render:

JSX
const themeRef = useRef(theme);
useLayoutEffect(() => {
  themeRef.current = theme;
});
// …inside the effect: showNotification('Connected!', themeRef.current)

It works, but it’s verbose and easy to get subtly wrong. useEffectEvent is the official, lint-aware replacement.

Ask yourself: “Should a change to this value restart the synchronisation?” If yes, it’s a dependency. If no, read it inside an Effect Event.

Exercise

Log page visits without over-firing

PageTracker({ url, cartCount, log }) should call log(url, cartCount) every time url changes — but NOT when only cartCount changes. The logged cart count must still be the latest value. Implement it with useEffect and useEffectEvent, with no lint-rule suppressions.

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

export function PageTracker({ url, cartCount, log }) {
  // your code here
  return null;
}

Summary

  • Effects re-run when any reactive value they read changes — sometimes that’s too often.
  • useEffectEvent(fn) creates an Effect Event: a function that always sees the latest props and state but isn’t reactive.
  • Call Effect Events only from inside effects; don’t pass them to other components or call them during render.
  • Effect Events are never listed in dependency arrays; the lint rule knows this.
  • Pass values that should trigger the logic as arguments (like url), and read the rest inside.