Sub topic 8
Rules of Effect Events
This chapter assumes you already know how to declare an Effect Event with useEffectEvent and call it from inside an Effect, and that you understand why it always reads the latest props and state. It also assumes you are comfortable with useEffect cleanup and the dependency array.
An Effect Event gives up something important: it is not reactive. React does not re-synchronize anything when the values it reads change. That is safe only if the Effect Event runs in the places React expects. The rules below define those places. Each rule exists to prevent a specific bug.
The rules at a glance
| Rule | What to do | What goes wrong if you break it |
|---|---|---|
| Call only from Effects | Call it inside `useEffect`, `useLayoutEffect`, or `useInsertionEffect`, or inside callbacks those Effects set up | Render-time calls make output depend on non-reactive values; React throws an error |
| Never list it as a dependency | Leave it out of the dependency array | It can trigger re-runs you did not intend, which defeats its purpose |
| Do not pass it to other components or Hooks | Keep it local to the component or Hook that declares it | The receiver may call it during render or from an event handler, outside any Effect |
| Declare it next to the Effect that uses it | Keep the Effect Event and its Effect side by side | Readers lose track of which Effect owns which non-reactive logic |
| Do not use it as an event handler | Use a plain function for clicks, input, and submits | You hide logic from reactivity for no benefit and break the lint rules |
Rule 1: Call Effect Events only from inside Effects
An Effect Event is meant to be the non-reactive part of an Effect. Its only callers should be Effects, plus callbacks that an Effect creates, such as an interval, a socket listener, or a .then handler.
Rendering is the clearest violation. Rendering should compute JSX from current props and state, and the result should change when they change. If you call an Effect Event during render, the output depends on code that React deliberately leaves out of reactive tracking. React prevents this: calling an Effect Event while rendering throws an error.
import { useEffectEvent } from 'react';
function Timer({ onDone }) {
const onTick = useEffectEvent(() => {
onDone();
});
// Wrong: Effect Events must not be called during render
// onTick();
// Wrong: Effect Events must not be passed to other components or Hooks
// return <Child onTick={onTick} />;
return null;
}Here is the same component written correctly. The Effect Event is called only from a timeout that the Effect schedules.
import { useEffect, useEffectEvent } from 'react';
export default function Timer({ seconds, onDone }) {
const onFinish = useEffectEvent(() => {
onDone();
});
useEffect(() => {
const id = setTimeout(() => {
onFinish();
}, seconds * 1000);
return () => clearTimeout(id);
}, [seconds]);
return <p>Timer running for {seconds} seconds</p>;
}The timeout restarts when seconds changes, because that value decides when the timer finishes. It does not restart when the parent passes a new inline onDone function on every render, because onFinish reads the latest onDone at the moment it fires.
Rule 2: Never list an Effect Event as a dependency
The purpose of an Effect Event is to keep some values out of the dependency array. Adding the Effect Event itself to that array undoes the work.
// Wrong
useEffect(() => {
const id = setTimeout(() => onFinish(), seconds * 1000);
return () => clearTimeout(id);
}, [seconds, onFinish]);Do not depend on the identity of the function useEffectEvent returns. React does not promise it stays the same between renders, so you cannot list it as if it were a stable function the way you might list a useState setter. The dependency linter understands Effect Events: it does not ask you to add them and it flags them when you do. A later chapter covers how the linter handles them in more detail.
The fix is always the same. List the reactive values the Effect really synchronizes with, here seconds, and leave the Effect Event out.
Rule 3: Do not pass Effect Events to other components or Hooks
An Effect Event belongs to the component or custom Hook that declares it. Once you pass it out as a prop or as an argument to another Hook, you can no longer guarantee that the receiver calls it only from Effects. The child might call it from onClick, during render, or in an Effect whose dependencies you cannot see.
If a child needs a callback, pass the ordinary function. If the child needs to call that callback from its own Effect without re-synchronizing, the child declares its own Effect Event.
import { useEffect, useEffectEvent } from 'react';
function Child({ onTick }) {
const onTickEvent = useEffectEvent(() => {
onTick();
});
useEffect(() => {
const id = setInterval(() => onTickEvent(), 1000);
return () => clearInterval(id);
}, []);
return null;
}
export default function Parent() {
// A plain function is passed down, not an Effect Event
return <Child onTick={() => console.log('tick')} />;
}The same reasoning applies to Hooks. A custom Hook may wrap a callback it receives in its own Effect Event, and a later chapter builds a useInterval Hook that way. What you should not do is create an Effect Event in a component and then hand it to useSomething(onTick). Pass the original callback and let the Hook decide how to handle it.
Rule 4: Declare the Effect Event next to the Effect that uses it
This rule is about readability, not runtime behavior. An Effect Event is one piece of a particular Effect, the piece you split out because it should not react. Put it directly above that Effect so readers can see both parts together.
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]);
}If several unrelated Effects start sharing one Effect Event, take that as a hint. The shared logic may belong in a plain helper function, with each Effect wrapping it in its own small Effect Event.
Rule 5: An Effect Event is not an event handler
The name can mislead people. An Effect Event is called by an Effect when something happens in the outside world, such as a connection opening or a timer firing. It is not a replacement for onClick or onSubmit.
Regular event handlers already read the latest props and state, because React recreates them on each render and they run only when the user acts. Wrapping one in useEffectEvent gains you nothing, and passing the result to a JSX element breaks Rule 3. The linter reports it.
If a user action and an Effect both need the same logic, put the logic in a plain function and call it from both places:
import { useEffect, useEffectEvent } from 'react';
function Toast({ message, theme, autoShow }) {
function show() {
showNotification(message, theme);
}
const onAutoShow = useEffectEvent(() => {
show();
});
useEffect(() => {
if (autoShow) {
onAutoShow();
}
}, [autoShow]);
return <button onClick={show}>Show</button>;
}The button calls show directly. The Effect calls it through onAutoShow, so changes to message or theme do not cause it to fire again.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Calling the Effect Event in the component body | React throws an error during render | Move the call into an Effect, or compute the value in render without an Effect Event |
| Adding it to the dependency array | Lint warning, possible extra re-runs | Remove it and list only the real reactive values |
| Passing it as a prop | Lint error; the child may call it outside Effects | Pass the plain callback and let the child wrap it |
| Using it as `onClick` | Lint error; no benefit | Use a plain function |
| Moving reactive logic into it to silence the linter | Effect fails to re-synchronize when it should | Keep values that decide what the Effect does in the Effect and its dependencies, or pass them in as arguments |
The last row matters most. An Effect Event should hold only logic that should not cause re-synchronization. If changing a value should restart the connection, timer, or subscription, that value belongs in the Effect's dependencies. Hiding it inside an Effect Event produces the same stale-synchronization bug you would get by suppressing the linter.
Exercises
Exercise
A component declares const onTick = useEffectEvent(() => setCount(c => c + step)); and renders <button onClick={onTick}>Tick</button>. Which rules does this break, and how should you fix it?
Show answer
It breaks two rules. It passes the Effect Event to another component (the button element), and it uses an Effect Event as an event handler, outside any Effect. Use a plain function instead: function handleTick() { setCount(c => c + step); } and <button onClick={handleTick}>. A regular handler already reads the latest step.
Exercise
A teammate writes useEffect(() => { const id = setInterval(() => onTick(), 1000); return () => clearInterval(id); }, [onTick]); where onTick comes from useEffectEvent. What is wrong, and what should the dependency array be?
Show answer
Effect Events must never be listed as dependencies. Their identity is not guaranteed to be stable, so listing one can restart the interval and defeats the purpose of using an Effect Event. The linter flags it. The Effect reads no other reactive values, so the array should be [].
Exercise
A parent creates const onMessage = useEffectEvent(msg => log(msg, userId)); and passes it as <Socket onMessage={onMessage} />. Socket subscribes to messages in its own Effect. Rewrite the design so it follows the rules.
Show answer
The parent passes a plain function: <Socket onMessage={msg => log(msg, userId)} />. Inside Socket, declare const onMessageEvent = useEffectEvent(msg => onMessage(msg)); and call onMessageEvent(msg) from the subscription callback in Socket's Effect. Leave onMessageEvent out of the dependencies. Socket then always calls the latest parent callback without resubscribing on every render.
Exercise
You move roomId into an Effect Event so the linter stops asking for it as a dependency, and the Effect now has [] as its dependencies. What bug follows, and why is this a misuse?
Show answer
When roomId changes, the Effect does not reconnect, so the component stays connected to the old room. roomId determines what the Effect synchronizes with, so it is reactive and must stay a dependency. An Effect Event should hold only logic that should not cause re-synchronization. Using one to hide a real dependency gives the same stale-synchronization bug as suppressing the linter.