Sub topic 5
Extracting Non-Reactive Logic with useEffectEvent
This chapter assumes you know closures and arrow functions in JavaScript, React function components with props and useState, and how useEffect works with a cleanup function and a dependency array. The previous chapter ended with a chat room that reconnected whenever the user changed the theme. Here you will fix that by moving the theme-reading code out of the Effect's reactive flow with useEffectEvent.
The Problem in One Sentence
The Effect has two jobs: it connects to a room, and it shows a notification once the connection succeeds. Only the first job should re-run when its inputs change. The second job just reads theme at the moment the connection opens. Because both jobs sit in the same Effect, theme became a dependency, and every theme toggle tears down the connection.
import { useEffect } from 'react';
import { createConnection } from './chat.js';
import { showNotification } from './notifications.js';
function ChatRoom({ roomId, theme }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.on('connected', () => {
showNotification('Connected!', theme);
});
connection.connect();
return () => connection.disconnect();
}, [roomId, theme]); // changing theme reconnects the chat
}You need a way to say "this piece of code runs from inside the Effect, but its reads should not count as dependencies." An Effect Event does that.
What an Effect Event Is
An Effect Event is a function you declare with the useEffectEvent Hook. Like an event handler, it holds logic that responds to something happening. It doesn't re-synchronize anything. The difference from an event handler is the trigger. A regular event handler runs when the user clicks or types. An Effect Event runs when your Effect calls it, for example inside a connected callback.
The code inside an Effect Event is non-reactive: the values it reads do not make the surrounding Effect re-run. When it does run, it still sees the current props and state.
The Refactor, Step by Step
Step 1: Find the code that reads but should not react
Look at each value the Effect reads and ask: "If this value changes, should the Effect redo its work?"
| Value | Read where | Should a change re-run the Effect? |
|---|---|---|
| `roomId` | `createConnection(roomId)` | Yes. A new room needs a new connection. |
| `theme` | `showNotification('Connected!', theme)` | No. The theme only styles a one-off message. |
The code that reads theme is the candidate for extraction. That code is the showNotification call.
Step 2: Declare the Effect Event at the top level of the component
Call useEffectEvent with a function that contains the non-reactive code. Hooks must run at the top level of the component, so you can't call it inside the Effect, inside a condition, or inside a loop.
const onConnected = useEffectEvent(() => {
showNotification('Connected!', theme);
});The name starts with on by convention, which signals that it represents something that happened ("the connection opened"), not a value.
Step 3: Call it from inside the Effect
Replace the inline code with a call to the Effect Event.
connection.on('connected', () => {
onConnected();
});Step 4: Remove the value from the dependency array
The Effect no longer reads theme directly. It reads onConnected, and Effect Events are never listed as dependencies. The array shrinks to [roomId].
The Complete Fixed Example
The three files below run in any React 19.2+ project, such as a Vite React template. The chat.js and notifications.js files are small fakes that log to the console so you can watch connections open and close.
// chat.js
export function createConnection(roomId) {
const handlers = {};
let timeoutId = null;
return {
on(event, callback) {
handlers[event] = callback;
},
connect() {
console.log('Connecting to "' + roomId + '"...');
timeoutId = setTimeout(() => {
if (handlers.connected) {
handlers.connected();
}
}, 100);
},
disconnect() {
clearTimeout(timeoutId);
console.log('Disconnected from "' + roomId + '"');
},
};
}// notifications.js
export function showNotification(message, theme) {
console.log('[' + theme + ' notification] ' + message);
}// App.jsx
import { useState, useEffect, useEffectEvent } from 'react';
import { createConnection } from './chat.js';
import { showNotification } from './notifications.js';
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]); // only roomId re-synchronizes the Effect
return <h1>Welcome to the {roomId} room!</h1>;
}
export default function App() {
const [roomId, setRoomId] = useState('general');
const [isDark, setIsDark] = useState(false);
return (
<>
<label>
Room:{' '}
<select value={roomId} onChange={(e) => setRoomId(e.target.value)}>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<label>
<input
type="checkbox"
checked={isDark}
onChange={(e) => setIsDark(e.target.checked)}
/>
Use dark theme
</label>
<hr />
<ChatRoom roomId={roomId} theme={isDark ? 'dark' : 'light'} />
</>
);
}Open the console and try both controls. Switching rooms logs a disconnect, a connect, and a notification. Toggling the theme logs nothing, because the Effect does not re-run. Switch rooms after toggling, and the notification shows the new theme.
What Happens on Each Render
The behavior is easier to trust once you see what happens on each render.
On every render, ChatRoom calls useEffectEvent with a fresh arrow function. That arrow function closes over the theme from that render. React stores the latest version internally and updates it before any Effects of that commit run. The function onConnected you get back forwards each call to whichever version React has stored most recently.
The connected callback registered by the Effect was created during the render where roomId last changed. If it called showNotification(..., theme) directly, it would use the theme captured back then. Because it calls onConnected() instead, the forwarding step reaches the newest closure and reads the current theme.
The next chapter covers this "always the latest value" behavior in more detail. For now, keep the split in mind. Values read in the Effect body are reactive. Values read inside the Effect Event are not.
Choosing What Goes Inside
The goal is to extract as little as possible. Move only the code whose reads should not trigger re-synchronization.
| Put inside the Effect Event | Keep in the Effect |
|---|---|
| Reads of values used for a side detail (theme, user settings, cart size for logging) | Code that sets up and tears down the external system |
| The response to something that happened (connected, tick, message received) | Reads of values that define *what* you synchronize with (`roomId`, `serverUrl`) |
| Calls to callbacks passed in as props when their identity changes every render | The cleanup function |
A common mistake is wrapping the whole Effect body in an Effect Event to make the dependency array empty. Then roomId stops being reactive. Switching rooms leaves you connected to the old one, and nothing warns you.
Common Errors During Extraction
These errors show up most often when people do this refactor for the first time.
- Declaring the Effect Event inside the Effect.
useEffectEventis a Hook, so calling it insideuseEffectbreaks the Rules of Hooks. Declare it at the component's top level. - Leaving the old value in the array. If
themestays in[roomId, theme], the Effect still reconnects. The linter flags it as unnecessary once nothing in the Effect body reads it. - Adding the Effect Event to the array. Writing
[roomId, onConnected]is wrong. The linter knows Effect Events are not dependencies, and listing one defeats the purpose. - Calling it outside an Effect. Calling
onConnected()during render or from a click handler is not allowed. Use a plain function or event handler there. A later chapter covers the full list of rules. - Using an older React version. The stable
useEffectEventexport ships in React 19.2. Older versions only offerexperimental_useEffectEventin experimental builds. The last chapter covers this.
Exercise
A component has useEffect(() => { const conn = createConnection(serverUrl, roomId); conn.on('message', (msg) => { if (!isMuted) playSound(); addMessage(msg); }); conn.connect(); return () => conn.disconnect(); }, [serverUrl, roomId, isMuted]); where addMessage comes from a stable useState setter wrapper. Muting the chat reconnects it. Which code should move into an Effect Event, and what is the final dependency array?
Show answer
Move the per-message handling that reads isMuted into an Effect Event declared at the top level, for example const onMessage = useEffectEvent((msg) => { if (!isMuted) playSound(); addMessage(msg); });, then register conn.on('message', (msg) => onMessage(msg)). serverUrl and roomId define which connection to open, so they stay. The final array is [serverUrl, roomId].
Exercise
A teammate "fixes" the reconnect bug by writing const onSetup = useEffectEvent(() => { const c = createConnection(roomId); c.on('connected', () => showNotification('Connected!', theme)); c.connect(); return c; }); and useEffect(() => { const c = onSetup(); return () => c.disconnect(); }, []);. Theme toggles no longer reconnect. What new bug did they introduce?
Show answer
roomId is now read only inside the Effect Event, so it is no longer reactive. With an empty dependency array, the Effect runs once on mount. Selecting a different room keeps the user connected to the original room. Only the notification code belongs in the Effect Event, and roomId must stay in the Effect body and the dependency array.