Sub topic 3
How Dependencies Make Effects Re-synchronize
This chapter assumes you know function components, useState, and the basics of useEffect, including cleanup functions. In the previous chapter you saw which values count as reactive. This chapter covers what React does with them: it compares the dependency array on every render to decide whether an Effect should stop and start again.
An Effect Is a Start and a Stop
It helps to think of an Effect as a process with two parts rather than as a component lifecycle event. The setup function starts synchronizing with an external system, such as a chat server. The cleanup function stops that synchronization. React may run this start/stop pair many times while the component stays on screen.
// chat.js
export function createConnection(roomId) {
return {
connect() {
console.log(`Connecting to "${roomId}"...`);
},
disconnect() {
console.log(`Disconnected from "${roomId}"`);
},
};
}// ChatRoom.js
import { useEffect } from 'react';
import { createConnection } from './chat.js';
export default function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <h1>Welcome to {roomId}</h1>;
}What React Does After Each Render
After every render, React looks at the dependency array and compares each item with its value from the previous render, using Object.is. If every item is the same, React skips the Effect. If any item differs, React re-synchronizes. It runs the cleanup from the last render first, then runs the setup again with the new values.
If roomId changes from "general" to "travel", the console shows:
Disconnected from "general"
Connecting to "travel"...In development, Strict Mode also runs setup, cleanup, and setup once more when the component mounts. This extra cycle checks that your cleanup really undoes the setup.
The Three Forms of the Dependency Array
| Array | When the Effect re-synchronizes |
|---|---|
| `[roomId]` | On mount, then whenever `roomId` changes |
| `[]` | Only on mount. It cleans up on unmount |
| omitted | After every render |
You don't pick dependencies to get a schedule you like. The rule is that every reactive value the Effect reads must appear in the array. The react-hooks/exhaustive-deps lint rule enforces this. If you leave roomId out, the Effect keeps the connection to the first room even after the prop changes.
Common Errors
- Missing dependency. The Effect reads a stale value from an earlier render. Add the value to the array instead of silencing the linter.
- Unstable dependency. An inline object or function forces a reconnect on every render. Move it inside the Effect, or move it outside the component.
- Assuming
[]means "run once." That only holds if the Effect reads no reactive values. Otherwise the array is just wrong.
So far this rule works as intended: reading roomId is exactly why the Effect should reconnect. The next chapter covers the case where it doesn't. An Effect sometimes reads a value only to use it, and it should not reconnect when that value changes.
Exercise
A component renders <ChatRoom roomId="music" /> three times in a row, and then renders <ChatRoom roomId="news" />. Using the ChatRoom code above, outside Strict Mode, what does the console log across all four renders?
Show answer
Connecting to "music"... after the first render. Renders two and three log nothing, because roomId is still "music" and Object.is reports no change. The fourth render logs Disconnected from "music" and then Connecting to "news"....
Exercise
An Effect has the dependency array [options], and options is defined in the component body as const options = { serverUrl, roomId };. Why does the Effect reconnect after every render, and how do you fix it?
Show answer
Each render creates a new object, so Object.is treats options as changed every time. Build the object inside the Effect and depend on [serverUrl, roomId], which are primitives that only change when their values change.