Sub topic 13
When useEffectEvent Is the Wrong Tool
This chapter assumes you know how useEffectEvent works: how to declare an Effect Event, how it reads the latest props and state, and the rule that you call it only from inside Effects. Earlier chapters showed where it fits. This one covers the cases where it does not fit. In these cases an Effect Event hides a bug, adds code you don't need, or fixes a problem that should be fixed another way.
The main question to ask is this: should this value, when it changes, cause the Effect to synchronize again? An Effect Event is the right answer only when the answer is "no" and the logic really belongs inside an Effect. If either part is false, use a different tool.
Decision Criteria at a Glance
| Situation | Wrong tool | Better tool |
|---|---|---|
| Code runs because the user clicked or typed | Effect plus Effect Event | Event handler |
| A value is derived from props or state | Effect that sets state | Compute during render, or `useMemo` |
| A value defines *what* you synchronize with | Effect Event that hides it | Keep it as a dependency |
| State is updated from its previous value | Effect Event that reads the state | Updater function `setX(x => ...)` |
| An object or function is recreated every render | Effect Event wrapper | Create it inside the Effect |
| A callback is passed to a child component | Effect Event | Plain function or `useCallback` |
| A mutable value is read in event handlers, not Effects | Effect Event | `useRef` |
Mistake 1: Logic That Belongs in an Event Handler
An Effect Event is still part of an Effect. It runs only because an Effect called it. If the logic runs because the user did something, it does not belong in an Effect, so it does not belong in an Effect Event either.
Here is a common anti-pattern. A flag is set in state so that an Effect can react to it:
import { useState, useEffect, useEffectEvent } from 'react';
import { sendMessage } from './chat.js';
function Composer({ roomId }) {
const [text, setText] = useState('');
const [submitted, setSubmitted] = useState(false);
// Wrong: an Effect used as a delayed event handler
const onSubmit = useEffectEvent(() => {
sendMessage(roomId, text);
});
useEffect(() => {
if (submitted) {
onSubmit();
setSubmitted(false);
}
}, [submitted]);
return (
<>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={() => setSubmitted(true)}>Send</button>
</>
);
}This code sends messages, but it renders twice, uses a state variable only as a signal, and reads like a puzzle. The user's click is the cause, so put the work in the click handler:
import { useState } from 'react';
import { sendMessage } from './chat.js';
function Composer({ roomId }) {
const [text, setText] = useState('');
function handleSend() {
sendMessage(roomId, text);
setText('');
}
return (
<>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={handleSend}>Send</button>
</>
);
}Event handlers already read the latest props and state, creates them fresh on each render. They don't need useEffectEvent.
Mistake 2: Hiding a Value the Effect Should React To
This misuse is the most dangerous, because the linter can no longer catch it. An Effect Event removes a value from the dependency array. If that value decides which external system you connect to, removing it breaks the Effect.
import { useEffect, useEffectEvent } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
// Wrong: roomId is what the Effect synchronizes with
const getRoomId = useEffectEvent(() => roomId);
useEffect(() => {
const connection = createConnection(getRoomId());
connection.connect();
return () => connection.disconnect();
}, []); // never reconnects when roomId changes
}The linter is satisfied, but when the user switches rooms, the component stays connected to the first room. The fix is to list roomId in the dependency array, because it is reactive logic:
import { useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
}Here is a quick test. Imagine the value changes while the Effect is running. Does the user expect the side effect to start over? A new roomId means a new connection, so it is reactive. A new theme only changes how a future notification looks, so it is non-reactive.
Mistake 3: Using an Effect for Derived Values
Sometimes developers reach for an Effect Event because an Effect "needs" a value only to compute other state. Usually the whole Effect is unnecessary:
import { useState } from 'react';
function Cart({ items, taxRate }) {
const [coupon, setCoupon] = useState(0);
// Computed during render: always correct, no Effect needed
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
const total = (subtotal - coupon) * (1 + taxRate);
return (
<>
<p>Total: {total.toFixed(2)}</p>
<button onClick={() => setCoupon(5)}>Apply coupon</button>
</>
);
}If computing the value is expensive, wrap it in useMemo. Effects and Effect Events are for synchronizing with things outside React, such as connections, timers, browser APIs, and analytics. They are not for keeping one piece of React state in step with another.
Mistake 4: Skipping a Simpler Restructure
Some dependencies disappear when you restructure the code. Prefer these fixes before reaching for an Effect Event, because they add no new concept.
Updater functions
If an Effect reads state only to compute the next value of that same state, use an updater function:
import { useState, useEffect } from 'react';
function Ticker() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount((c) => c + 1); // no need to read count
}, 1000);
return () => clearInterval(id);
}, []);
return <h1>{count}</h1>;
}The timer chapter used an Effect Event because the tick read a second value, increment. When the only value you read is the state you are updating, the updater is enough.
Objects and functions created during render
An object literal is a new object on every render. As a dependency, it restarts the Effect every time. Wrapping it in an Effect Event hides the problem instead of fixing it. Create the object inside the Effect, and depend on the primitive values it is built from:
import { useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId, serverUrl }) {
useEffect(() => {
const options = { serverUrl, roomId };
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId, serverUrl]);
}Now the Effect restarts only when roomId or serverUrl actually change, which is the correct behavior.
Mistake 5: Using Effect Events Outside Effects
Earlier chapters covered the rules: don't call an Effect Event during rendering, and don't pass it to other components or Hooks. A few situations tempt people to break these rules:
- Stable callbacks for children. If a memoized child re-renders because a callback prop changes on every render, use
useCallbackor pass a plain function. An Effect Event's identity is not guaranteed for this purpose, and the child might call it during rendering. - Event handlers. Calling an Effect Event from
onClickworks by accident in some versions, but it breaks the rule and gains nothing, since the handler already sees fresh values. - Calling it from a custom Hook's return value. A custom Hook may create an Effect Event and call it from its own Effects, as in
useInterval. It must not return the Effect Event to the caller.
Effect Events Versus Refs
Before useEffectEvent, people stored the latest value in a ref and read ref.current inside the Effect. Refs are still the right tool in some cases:
| Need | Use |
|---|---|
| Read latest props or state from an Effect's callback | `useEffectEvent` |
| Keep a mutable value that is not rendered, such as a timer ID or DOM node | `useRef` |
| Remember a value across renders and read it in event handlers | `useRef` |
| Track the previous value of a prop | `useRef`, or store it in state |
The hand-written "latest ref" pattern has a gotcha. You must update ref.current in an Effect or layout Effect, not during render, and the update order between Effects is easy to get wrong. useEffectEvent takes care of this for you, so prefer it for the Effect-callback case. Don't swap a ref for an Effect Event when the value is mutable bookkeeping that has nothing to do with Effects.
Failure Modes Summary
- Stale synchronization. A reactive value is hidden in an Effect Event, so the Effect stays attached to an old room, URL, or subscription.
- Double renders and indirection. User-triggered logic goes through state flags and Effects instead of an event handler.
- Unnecessary Effects. Derived values are synced into state instead of being computed during render.
- Masking design issues. Objects recreated during render are wrapped instead of moved inside the Effect.
- Rule violations. Effect Events are passed to children, returned from Hooks, or called during render. The linter flags these, so don't silence it.
Exercise
A component logs analytics with logVisit(url) and shows a toast in the current theme when the page loads. A teammate writes const getUrl = useEffectEvent(() => url);, calls logVisit(getUrl()) inside an Effect with an empty dependency array, and also reads theme inside the Effect Event. What is wrong, and how should it be fixed?
Show answer
url is reactive. A new URL means a new visit that should be logged, but with the empty dependency array the Effect runs only once, so later visits are never logged. Keep url in the dependency array and pass it to the Effect Event as an argument, for example onVisit(url) inside an Effect with [url]. The Effect Event can still read theme without depending on it.
Exercise
An Effect sets up an interval that calls setSeconds(seconds + 1), and the linter wants seconds as a dependency. Should you wrap the tick in an Effect Event?
Show answer
No. Use the updater form setSeconds((s) => s + 1). The Effect then no longer reads seconds, the dependency array can be empty, and you don't need an Effect Event. Reach for useEffectEvent only if the tick reads some other value that should not restart the interval.
Exercise
A form submits data when the user clicks Save. A developer puts the submit call in an Effect Event that runs from an Effect watching a saveRequested state flag. Name the better tool and one cost of the current approach.
Show answer
Call the submit logic directly in the button's click handler. The current approach causes an extra render, uses state only as a signal, and puts user-triggered logic inside an Effect. That makes the code harder to follow and can fire twice in development under Strict Mode.