Sub topic 4
When an Effect Reconnects for the Wrong Reason
This chapter assumes you know React function components, props, useState, and useEffect, including cleanup functions and the dependency array. Earlier chapters covered reactive values and how dependencies make an Effect re-synchronize. Here you will see that model produce behavior the user never asked for.
A Chat Room That Respects the Theme
Picture a chat room component. It connects to a server for the current roomId. When the connection succeeds, it shows a "Connected!" notification, styled with the current theme. Both roomId and theme come from props.
These two helper modules let the example run on its own:
// chat.js
export function createConnection(roomId) {
let handlers = {};
return {
connect() {
console.log('Connecting to', roomId);
setTimeout(() => handlers.connected?.(), 100);
},
on(event, handler) {
handlers[event] = handler;
},
disconnect() {
console.log('Disconnected from', roomId);
handlers = {};
},
};
}// notifications.js
export function showNotification(message, theme) {
console.log(`[${theme}] ${message}`);
}Here is the component:
import { useEffect } from 'react';
import { createConnection } from './chat.js';
import { showNotification } from './notifications.js';
export default 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
return <h1>Welcome to {roomId}</h1>;
}The Effect reads theme, so the dependency linter requires theme in the array. The code is correct by the rules of Effects. That correctness is what causes the problem.
What the User Sees
Suppose the user switches from light to dark mode while staying in the general room. React sees that theme changed, so it runs the cleanup and then runs the Effect again:
The console shows:
Disconnected from general
Connecting to general
[dark] Connected!The room never changed, yet the app dropped the socket, opened a new one, and announced a connection again. In a real app that can mean lost in-flight messages, a flicker of "reconnecting" UI, and extra load on the server.
Two Kinds of Logic in One Effect
The root cause is that this Effect mixes two kinds of logic:
| Code | Should it re-run when the value changes? | Why |
|---|---|---|
| `createConnection(roomId)` and `connect()` | Yes, on `roomId` | A different room needs a different connection. |
| `showNotification('Connected!', theme)` | No | The theme only affects how a one-off message looks. |
Connecting is reactive logic. It should stay in sync with roomId. Showing the notification acts more like an event handler. It responds to something that happened (the connection succeeded) and only needs to read whatever theme is at that moment. Inside a single Effect, though, React cannot tell these apart. Every reactive value the Effect reads becomes a dependency, and any dependency change restarts the whole Effect.
What a Fix Needs to Do
A proper solution has to meet three requirements at once:
- The connection re-synchronizes when
roomIdchanges, and only then. - The notification still uses the latest
theme, not a stale one. - The linter stays satisfied without being suppressed.
Plain Effects cannot do all three. You need a way to mark part of an Effect's code as non-reactive: it can read current props and state without making them dependencies. That is the job of an Effect Event, which the next chapter introduces with useEffectEvent.
Exercise
A Page component has an Effect that calls logVisit(url, shoppingCart.length) with dependencies [url, shoppingCart]. What goes wrong when the user adds an item to the cart, and which part of the logic is reactive?
Show answer
Adding an item changes shoppingCart, so the Effect re-runs and logs a second visit for the same page. Only url should be reactive, because a new URL means a new visit. The cart size is read at the moment of the visit and should not trigger another log entry.
Exercise
In the ChatRoom example, list the console output when roomId changes from "general" to "travel" while theme stays "light". Is this re-synchronization wanted?
Show answer
"Disconnected from general", "Connecting to travel", "[light] Connected!". Yes. A new room requires a new connection, so this re-run is correct.