Sub topic 3
How Dependencies Make Effects Re-synchronize
This chapter assumes you know JavaScript closures, React function components with useState, and basic useEffect usage with a cleanup function. The previous chapter covered which values count as reactive. This one explains what React does with those values once you list them in a dependency array: when it re-runs your Effect, how it decides, and what goes wrong when the list is inaccurate.
An Effect Is a Synchronization, Not a Lifecycle Hook
It helps to stop thinking of Effects as "run on mount" and "run on update." An Effect describes how to start synchronizing with an external system (a connection, a subscription, a timer) and how to stop. React's job is to keep that synchronization matching your current props and state.
Within the component's lifetime, React may start and stop the same Effect many times:
- The component mounts. React runs the setup code.
- The component re-renders with different reactive values. React runs the cleanup from the previous render, then runs setup again with the new values.
- The component unmounts. React runs the final cleanup.
Step 2 is re-synchronization. The dependency array tells React when step 2 is needed.
A Working Example
Here is a chat room that connects to a server. The chat module is a stub that logs what it does, so you can watch re-synchronization in the console.
// chat.js
export function createConnection(serverUrl, roomId) {
return {
connect() {
console.log(`Connecting to "${roomId}" at ${serverUrl}...`);
},
disconnect() {
console.log(`Disconnected from "${roomId}" at ${serverUrl}`);
},
};
}// App.js
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
}, [serverUrl, roomId]);
return (
<>
<label>
Server URL:{' '}
<input value={serverUrl} onChange={(e) => setServerUrl(e.target.value)} />
</label>
<h1>Welcome to the {roomId} room!</h1>
</>
);
}
export default function App() {
const [roomId, setRoomId] = useState('general');
return (
<>
<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>
<hr />
<ChatRoom roomId={roomId} />
</>
);
}If you switch the room from general to travel, the console shows:
Disconnected from "general" at https://localhost:1234
Connecting to "travel" at https://localhost:1234...The cleanup ran with the old roomId. That is because the cleanup function is a closure created during the earlier render, and it captured that render's connection. This is what you want: you disconnect from the room you were actually in.
Each keystroke in the server URL input also triggers a disconnect and reconnect, because serverUrl is a dependency and its value changed.
How React Compares Dependencies
After every render, React looks at the dependency array you passed this time and the one from the previous commit. It compares them position by position using Object.is. If every entry is the same, React skips the Effect. If any entry differs, React runs cleanup and then setup.
Object.is acts like ===, with two edge cases: Object.is(NaN, NaN) is true, and Object.is(0, -0) is false. The consequences for each kind of value:
| Value kind | Compared by | Re-synchronizes when |
|---|---|---|
| String, number, boolean | Value | The value changes |
| `null` / `undefined` | Value | It switches to or from another value |
| Object or array | Reference | A new object is created, even with identical contents |
| Function | Reference | A new function is created, which happens on every render if it's defined in the component body |
React does not deep-compare. Two objects with the same keys and values are still different dependencies if they're separate objects.
The Three Shapes of a Dependency Array
| You write | React runs the Effect |
|---|---|
| `useEffect(fn, [a, b])` | After the first render, and after any render where `a` or `b` changed |
| `useEffect(fn, [])` | After the first render only. Cleanup runs on unmount |
| `useEffect(fn)` | After every render |
An empty array is a claim, not a request. It says "this Effect reads no reactive values." If the Effect actually reads roomId, the empty array doesn't make the Effect ignore roomId changes in a safe way. The Effect keeps the roomId from the first render and silently goes out of sync. Later chapters cover why that leads to stale-value bugs.
You Don't Choose the Dependencies
The react-hooks/exhaustive-deps lint rule checks that every reactive value the Effect reads is listed. Reactive values are props, state, and anything declared in the component body that is computed from them. If you remove serverUrl from the array above, the linter reports:
React Hook useEffect has a missing dependency: 'serverUrl'.
Either include it or remove the dependency array.The working model: the code inside the Effect determines the dependencies. If you want a different dependency list, change the code so that it reads different values. Don't edit the list on its own.
Values the linter does not require:
- Module-level constants and imports, such as
createConnection. They never change between renders. - The
setfunctions returned byuseStateand thedispatchfunction fromuseReducer. React keeps them stable. - Ref objects from
useRef. The ref object is stable, thoughref.currentis not reactive, so reading it won't trigger re-synchronization.
You can make a value non-reactive by moving it out of the component:
import { useEffect } from 'react';
import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234'; // not reactive
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // serverUrl is no longer needed
}Common Error: Objects and Functions Created During Render
This version reconnects after every render, even when roomId stays the same:
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
const options = { serverUrl: 'https://localhost:1234', roomId };
useEffect(() => {
const connection = createConnection(options.serverUrl, options.roomId);
connection.connect();
return () => connection.disconnect();
}, [options]); // new object every render
return <input value={message} onChange={(e) => setMessage(e.target.value)} />;
}Typing in the input updates message and re-renders ChatRoom. That render creates a new options object. Object.is(oldOptions, newOptions) is false, so React disconnects and reconnects on every keystroke.
The fix is to create the object inside the Effect so that the Effect depends only on primitive values:
useEffect(() => {
const options = { serverUrl: 'https://localhost:1234', roomId };
const connection = createConnection(options.serverUrl, options.roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);Functions defined in the component body cause the same problem. If you get an object or function from props, read the primitive fields you need outside the Effect (const { roomId } = options;) and depend on those.
Development-Only Extra Re-synchronization
In development with <StrictMode>, React mounts each component, immediately runs every Effect's cleanup, and then runs setup again. You'll see a connect, disconnect, connect sequence on first load. This checks that your cleanup correctly undoes your setup. If the app behaves the same after that extra cycle, your Effect is written correctly. Production builds don't do this.
The Tension This Creates
The rules so far are strict. Every reactive value the Effect reads becomes a dependency, and every change to a dependency tears down and rebuilds the synchronization. For roomId and serverUrl, that is correct, since a different room needs a different connection.
Sometimes, though, an Effect reads a value only to use it at some moment, for example a theme color for a notification shown when the connection opens. The rules still make that value a dependency, and changing it would still reconnect the chat. The next chapter looks at that problem directly.
Exercise
A component has const filters = { category, minPrice }; in its body and an Effect that fetches products using filters, with [filters] as its dependency array. Users report that the product list refetches whenever they type in an unrelated search box in the same component. Explain why, and give a fix.
Show answer
Typing updates state, which re-renders the component and creates a new filters object. React compares dependencies with Object.is, which compares objects by reference, so the new object counts as a change and the Effect re-runs. Fix it by depending on primitives: build the object inside the Effect, or use category and minPrice directly, and list [category, minPrice] as dependencies.
Exercise
In the chat example, the user switches from room "music" to room "travel". In what order do the console messages appear, and which roomId does the cleanup log? Why?
Show answer
First Disconnected from "music" ..., then Connecting to "travel" .... The cleanup is a closure from the previous render, so it captured that render's connection for "music". React always runs the old cleanup before the new setup.
Exercise
A teammate changes an Effect's dependency array from [roomId] to [] "so it only connects once," while the Effect still calls createConnection(serverUrl, roomId). What happens when roomId changes, and what does the linter report?
Show answer
The Effect doesn't re-run, so the component stays connected to the first room while the UI shows the new one. The Effect's closure keeps the initial roomId. The exhaustive-deps rule reports roomId as a missing dependency, because the code inside the Effect reads it.