Sub topic 5
Extracting Non-Reactive Logic with useEffectEvent
This chapter assumes you know how useEffect and its dependency array work, and how closures capture values from a render. The previous chapter showed a chat room that disconnects and reconnects whenever theme changes, even though theme only affects how a notification looks. Here you fix that by moving the theme-reading code out of the Effect's reactive logic.
Splitting the Effect into Two Parts
Look at what the chat Effect does and ask which parts should respond to changes:
- Connecting to the room depends on
roomId. A new room needs a new connection, so this part is reactive. - Showing the "Connected!" notification reads
theme, but a theme change should not cause a reconnect. This part is non-reactive. It should run when the connection event fires and use whateverthemeis current at that moment.
useEffectEvent is a React Hook that wraps non-reactive logic in a function called an Effect Event. An Effect Event can read props and state, but the values it reads do not become dependencies of your Effect.
Declaring an Effect Event
Call useEffectEvent at the top level of your component, the same place you call other Hooks. Pass it a function. It returns a function you can call from inside your Effect.
// chat.js
export function createConnection(roomId) {
let handlers = {};
let timeoutId;
return {
on(event, handler) {
handlers[event] = handler;
},
connect() {
console.log('Connecting to ' + roomId);
timeoutId = setTimeout(() => handlers.connected?.(), 500);
},
disconnect() {
clearTimeout(timeoutId);
console.log('Disconnected from ' + roomId);
},
};
}// notifications.js
export function showNotification(message, theme) {
console.log(`[${theme}] ${message}`);
}// ChatRoom.js
import { useEffect, useEffectEvent } from 'react';
import { createConnection } from './chat.js';
import { showNotification } from './notifications.js';
export default 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 {roomId}</h1>;
}Here is what changed from the broken version:
- The notification code moved into
onConnected, an Effect Event. - The Effect calls
onConnected()from the connection'sconnectedhandler. themeis no longer in the dependency array.onConnectedis not listed either.
If you switch the theme now, the console shows no reconnect. If you switch the room, the Effect cleans up and connects again, and the notification uses the theme that is current when the connection succeeds.
Thinking of It as an Event Handler for Effects
An Effect Event works like an event handler. A click handler runs when the user clicks and reads current state without making anything re-synchronize. An Effect Event runs when something your Effect set up fires, such as a connection opening or a timer ticking, and it also reads current values.
| Code location | Triggered by | Reads values reactively? |
|---|---|---|
| Event handler | A user interaction | No |
| Effect body | A change in its dependencies | Yes |
| Effect Event | A call from inside an Effect | No |
Common Mistakes
- Calling it during render. Effect Events are meant to be called from Effects, not from the component body.
- Adding it to the dependency array. It is intentionally non-reactive, so leave it out.
- Wrapping everything. If a value should restart the Effect, keep it in the Effect and in its dependencies.
Exercise
A component logs analytics with useEffect(() => { logEvent('opened', roomId, userName); }, [roomId, userName]);. Logging should happen once per room, but should include the current userName. How do you restructure it with useEffectEvent?
Show answer
Move the logging into an Effect Event, for example const onOpened = useEffectEvent(() => { logEvent('opened', roomId, userName); });, then call it from useEffect(() => { onOpened(); }, [roomId]);. Only roomId stays in the dependency array, so a change to userName no longer triggers a new log entry, and the next log still reads the latest userName.
Exercise
After the fix in this chapter, the theme changes from "light" to "dark" while the room stays the same. Does the chat reconnect? If the room later changes, which theme does the notification use?
Show answer
The chat does not reconnect, because theme is not an Effect dependency. When the room changes, the Effect reconnects, and the notification uses "dark", the theme current when the connected event fires.