Sub topic 4
When an Effect Reconnects for the Wrong Reason
This chapter assumes you know how to write a useEffect with a cleanup function, and that every reactive value an Effect reads belongs in its dependency array. Earlier chapters covered both. Here we look at a case where following that rule correctly still gives behavior you don't want. The Effect re-synchronizes because of a value it only reads, not because of a value it actually depends on.
The Scenario: A Chat Room with a Theme
A chat room component connects to a server for the selected room. When the connection succeeds, it shows a "Connected!" notification. The notification's style follows the current theme, light or dark.
Below is a complete, runnable version. The two helper modules are stubs that log to the console, so you can watch what happens.
// chat.js
export function createConnection(roomId) {
let connectedCallback = null;
let timeoutId = null;
return {
connect() {
console.log('Connecting to "' + roomId + '"...');
timeoutId = setTimeout(() => {
if (connectedCallback) connectedCallback();
}, 100);
},
on(event, callback) {
if (event !== 'connected') {
throw new Error('Only "connected" is supported.');
}
connectedCallback = callback;
},
disconnect() {
clearTimeout(timeoutId);
console.log('Disconnected from "' + roomId + '"');
},
};
}// notifications.js
export function showNotification(message, theme) {
console.log('[' + theme + ' notification] ' + message);
}// App.js
import { useState, 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
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'} />
</>
);
}This code is correct as far as the rules go. The Effect reads ``, both are reactive, and both are listed. The dependency linter is satisfied, and no value is stale.
Tracing What Happens When the Theme Changes
Check the box to switch to the dark theme and watch the console:
Disconnected from "general"
Connecting to "general"...
[dark notification] Connected!The user changed a visual preference, and the chat dropped its connection and reconnected to the same room. Nothing about the connection needed to change.
In this demo the cost is a few log lines. In a real app the same pattern can cause visible problems:
- Messages that arrive during the gap get dropped, or the client fetches history again.
- The server sees extra connections and may rate-limit the client.
- Presence indicators flicker ("Alice left", "Alice joined").
- The user gets a second "Connected!" notification they never expected.
Why React Does This
React did exactly what the code told it to. An Effect is one unit of synchronization. React has no way to look inside the Effect body and tell which lines care about which values. When any dependency changes, React stops the whole synchronization and starts it again.
The problem is that the Effect mixes two kinds of logic:
| Logic | Values it reads | Should a change to that value restart it? |
|---|---|---|
| Create and open the connection | `roomId` | Yes. A different room needs a different connection. |
| Show a notification when connected | `theme` | No. The notification should use the current theme, but a theme change is not a reason to reconnect. |
Connecting is reactive logic. It exists to keep the outside world in sync with roomId. Showing the notification is closer to an event handler. It responds to something that happened (the server said "connected"), and when it runs it wants the latest theme. That is the same way a click handler reads the latest state without re-running when that state changes.
The notification code sits inside the Effect, so its reads count as the Effect's reads. theme becomes a dependency, and the Effect inherits a reason to re-synchronize that belongs only to the notification.
The Diagnostic Question
To spot this problem, go through each value your Effect reads and ask:
> If only this value changed, should the synchronization stop and start again?
If the answer is yes for every value, the Effect is fine. If the answer is no for some value, the Effect contains non-reactive logic that has ended up in a reactive context. Common signs:
- The value is used only inside a callback that the Effect registers, such as
on('connected'),setInterval, oraddEventListener. - The value adjusts how something is reported or presented (theme, locale, a log payload) but has no effect on what is synchronized.
- When you explain the Effect out loud, you say "when X happens, use the current Y". That makes Y something read at event time, not a thing to sync with.
The Same Problem in Other Shapes
This pattern is not specific to chat. The same mismatch appears whenever an Effect both sets something up and reports or reacts using extra values.
Analytics. You want to log one visit per URL and include the cart size:
import { useEffect } from 'react';
import { logVisit } from './analytics.js';
function Page({ url, shoppingCart }) {
useEffect(() => {
logVisit(url, shoppingCart.length);
}, [url, shoppingCart]); // adding an item logs a fake "visit"
}A new url is a new visit. A new shoppingCart is not, but this Effect logs another visit every time the cart changes.
Timers. An interval adds increment to a counter every second:
import { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(0);
const [increment, setIncrement] = useState(1);
useEffect(() => {
const id = setInterval(() => {
setCount((c) => c + increment);
}, 1000);
return () => clearInterval(id);
}, [increment]); // each click restarts the interval
return (
<>
<h1>{count}</h1>
<button onClick={() => setIncrement((i) => i + 1)}>
Increment by {increment}
</button>
</>
);
}Each click clears the interval and creates a new one, which resets the one-second countdown. If the user clicks faster than once a second, the counter never ticks at all.
In both cases the dependency list is honest. The design is what's wrong: one value belongs to the setup, and the other belongs to something that happens later.
Fixes That Look Reasonable but Fail
Removing theme from the array and silencing the linter. The Effect stops reconnecting, but its connected callback now keeps the theme from the render that last ran the Effect. Switch to dark mode, then change rooms, and the notification may still be light. A later chapter covers why this produces stale-value bugs and why the lint rule is right to complain.
Moving theme out of props into a module-level variable. It is no longer reactive, but it also no longer updates the UI or stays in sync with React state. You've traded one bug for another.
Storing theme in a ref by hand. This can work, but you have to write the ref update yourself, remember to keep it current, and explain the pattern to every reader. It is the manual version of what the next chapter gives you as a built-in.
Splitting into two Effects. That helps when the pieces are independent, but here the notification has to run inside the connection's connected callback. You can't move that callback into a separate Effect without creating a second connection.
What We Need
The requirements are now clear. We need a way to:
- Keep connecting inside the Effect, reacting to
roomId. - Pull the notification logic out so its reads don't count as the Effect's dependencies.
- Still have that logic see the latest
themewhenever it runs.
The linter must also stay on and accurate. The next chapter introduces useEffectEvent, which meets all three.
Exercise
A component subscribes to a stock price feed with subscribe(symbol, onPrice) inside an Effect. In onPrice it calls formatPrice(price, currency) and shows the result. Both symbol and currency are props, and the dependency array is [symbol, currency]. Which dependency causes an unwanted re-subscription, and why?
Show answer
currency. A new symbol needs a new subscription, so that change should re-synchronize the Effect. currency only affects how each incoming price is formatted, which happens at event time inside onPrice. Changing it should not tear down and rebuild the feed subscription.
Exercise
A teammate fixes the chat room by changing the dependency array to [roomId] and adding // eslint-disable-next-line react-hooks/exhaustive-deps. Describe a sequence of user actions that shows the bug this introduces.
Show answer
Start in the "general" room with the light theme. Switch to the dark theme: nothing reconnects, which looks fixed. Wait until the connection is already up, then switch back to light and change rooms. The Effect's callback uses theme from the render where the Effect last ran, so depending on the timing the notification can show an outdated theme. In general, the callback captures whatever theme existed the last time roomId changed, not the current one.
Exercise
For the Timer example, explain why clicking the button faster than once per second can stop the count from ever increasing.
Show answer
Each click changes increment, which is a dependency. React runs the cleanup (clearInterval) and starts a new interval, so the one-second wait starts over. If clicks come less than a second apart, no interval ever reaches its first tick.