'Removing Effect Dependencies'·续2
```js {expectedErrors: {'react-compiler': [10]}} import { useState, useEffect } from 'react'; import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) { const [message, setMessage] = useState('');
// Temporarily disable the linter to demonstrate the problem // eslint-disable-next-line react-hooks/exhaustive-deps const options = { serverUrl: serverUrl, roomId: roomId };
useEffect(() => { const connection = createConnection(options); connection.connect(); return () => connection.disconnect(); }, [options]);
return ( <>
Welcome to the {roomId} room!
setMessage(e.target.value)} /> </> ); }export default function App() { const [roomId, setRoomId] = useState('general'); return ( <>
```js src/chat.js
export function createConnection({ serverUrl, roomId }) {
// A real implementation would actually connect to the server
return {
connect() {
console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...');
},
disconnect() {
console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl);
}
};
}
input { display: block; margin-bottom: 20px; }
button { margin-left: 10px; }
In the sandbox above, the input only updates the message state variable. From the user's perspective, this should not affect the chat connection. However, every time you update the message, your component re-renders. When your component re-renders, the code inside of it runs again from scratch.
A new options object is created from scratch on every re-render of the ChatRoom component. React sees that the options object is a different object from the options object created during the last render. This is why it re-synchronizes your Effect (which depends on options), and the chat re-connects as you type.
This problem only affects objects and functions. In JavaScript, each newly created object and function is considered distinct from all the others. It doesn't matter that the contents inside of them may be the same!
```js {7-8} // During the first render const options1 = { serverUrl: 'https://localhost:1234', roomId: 'music' };
// During the next render const options2 = { serverUrl: 'https://localhost:1234', roomId: 'music' };
// These are two different objects! console.log(Object.is(options1, options2)); // false
**Object and function dependencies can make your Effect re-synchronize more often than you need.**
This is why, whenever possible, you should try to avoid objects and functions as your Effect's dependencies. Instead, try moving them outside the component, inside the Effect, or extracting primitive values out of them.
#### Move static objects and functions outside your component
If the object does not depend on any props and state, you can move that object outside your component:
```js {1-4,13}
const options = {
serverUrl: 'https://localhost:1234',
roomId: 'music'
};
function ChatRoom() {
const [message, setMessage] = useState('');
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, []); // ✅ All dependencies declared
// ...
This way, you prove to the linter that it's not reactive. It can't change as a result of a re-render, so it doesn't need to be a dependency. Now re-rendering ChatRoom won't cause your Effect to re-synchronize.
This works for functions too:
```js {1-6,12} function createOptions() { return { serverUrl: 'https://localhost:1234', roomId: 'music' }; }
function ChatRoom() { const [message, setMessage] = useState('');
useEffect(() => { const options = createOptions(); const connection = createConnection(options); connection.connect(); return () => connection.disconnect(); }, []); // ✅ All dependencies declared // ...
Since `createOptions` is declared outside your component, it's not a reactive value. This is why it doesn't need to be specified in your Effect's dependencies, and why it won't ever cause your Effect to re-synchronize.
#### Move dynamic objects and functions inside your Effect
If your object depends on some reactive value that may change as a result of a re-render, like a `roomId` prop, you can't pull it *outside* your component. You can, however, move its creation *inside* of your Effect's code:
```js {7-10,11,14}
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
useEffect(() => {
const options = {
serverUrl: serverUrl,
roomId: roomId
};
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]); // ✅ All dependencies declared
// ...
Now that options is declared inside of your Effect, it is no longer a dependency of your Effect. Instead, the only reactive value used by your Effect is roomId. Since roomId is not an object or function, you can be sure that it won't be unintentionally different. In JavaScript, numbers and strings are compared by their content:
```js {7-8} // During the first render const roomId1 = 'music';
// During the next render const roomId2 = 'music';
// These two strings are the same! console.log(Object.is(roomId1, roomId2)); // true
Thanks to this fix, the chat no longer re-connects if you edit the input:
```js
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
useEffect(() => {
const options = {
serverUrl: serverUrl,
roomId: roomId
};
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return (
<>
<h1>Welcome to the {roomId} room!</h1>
<input value={message} onChange={e => setMessage(e.target.value)} />
</>
);
}
export default function App() {
const [roomId, setRoomId] = useState('general');
return (
<>
<label>
Choose the chat 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>
<hr />
<ChatRoom roomId={roomId} />
</>
);
}
```js src/chat.js export function createConnection({ serverUrl, roomId }) { // A real implementation would actually connect to the server return { connect() { console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); } }; }
```css
input { display: block; margin-bottom: 20px; }
button { margin-left: 10px; }
However, it does re-connect when you change the roomId dropdown, as you would expect.
This works for functions, too:
```js {7-12,14} const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) { const [message, setMessage] = useState('');
useEffect(() => { function createOptions() { return { serverUrl: serverUrl, roomId: roomId }; }
const options = createOptions(); const connection = createConnection(options); connection.connect(); return () => connection.disconnect(); }, [roomId]); // ✅ All dependencies declared // ...
You can write your own functions to group pieces of logic inside your Effect. As long as you also declare them *inside* your Effect, they're not reactive values, and so they don't need to be dependencies of your Effect.
#### Read primitive values from objects
Sometimes, you may receive an object from props:
```js {1,5,8}
function ChatRoom({ options }) {
const [message, setMessage] = useState('');
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]); // ✅ All dependencies declared
// ...
The risk here is that the parent component will create the object during rendering:
```js {3-6}
This would cause your Effect to re-connect every time the parent component re-renders. To fix this, read information from the object *outside* the Effect, and avoid having object and function dependencies:
```js {4,7-8,12}
function ChatRoom({ options }) {
const [message, setMessage] = useState('');
const { roomId, serverUrl } = options;
useEffect(() => {
const connection = createConnection({
roomId: roomId,
serverUrl: serverUrl
});
connection.connect();
return () => connection.disconnect();
}, [roomId, serverUrl]); // ✅ All dependencies declared
// ...
The logic gets a little repetitive (you read some values from an object outside an Effect, and then create an object with the same values inside the Effect). But it makes it very explicit what information your Effect actually depends on. If an object is re-created unintentionally by the parent component, the chat would not re-connect. However, if options.roomId or options.serverUrl really are different, the chat would re-connect.
Calculate primitive values from functions
The same approach can work for functions. For example, suppose the parent component passes a function:
```js {3-8}
To avoid making it a dependency (and causing it to re-connect on re-renders), call it outside the Effect. This gives you the `roomId` and `serverUrl` values that aren't objects, and that you can read from inside your Effect:
```js {1,4}
function ChatRoom({ getOptions }) {
const [message, setMessage] = useState('');
const { roomId, serverUrl } = getOptions();
useEffect(() => {
const connection = createConnection({
roomId: roomId,
serverUrl: serverUrl
});
connection.connect();
return () => connection.disconnect();
}, [roomId, serverUrl]); // ✅ All dependencies declared
// ...
This only works for pure functions because they are safe to call during rendering. If your function is an event handler, but you don't want its changes to re-synchronize your Effect, wrap it into an Effect Event instead.
- Dependencies should always match the code.
- When you're not happy with your dependencies, what you need to edit is the code.
- Suppressing the linter leads to very confusing bugs, and you should always avoid it.
- To remove a dependency, you need to "prove" to the linter that it's not necessary.
- If some code should run in response to a specific interaction, move that code to an event handler.
- If different parts of your Effect should re-run for different reasons, split it into several Effects.
- If you want to update some state based on the previous state, pass an updater function.
- If you want to read the latest value without "reacting" it, extract an Effect Event from your Effect.
- In JavaScript, objects and functions are considered different if they were created at different times.
- Try to avoid object and function dependencies. Move them outside the component or inside the Effect.
Fix a resetting interval
This Effect sets up an interval that ticks every second. You've noticed something strange happening: it seems like the interval gets destroyed and re-created every time it ticks. Fix the code so that the interval doesn't get constantly re-created.
It seems like this Effect's code depends on count. Is there some way to not need this dependency? There should be a way to update the count state based on its previous value without adding a dependency on that value.
import { useState, useEffect } from 'react';
export default function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('✅ Creating an interval');
const id = setInterval(() => {
console.log('⏰ Interval tick');
setCount(count + 1);
}, 1000);
return () => {
console.log('❌ Clearing an interval');
clearInterval(id);
};
}, [count]);
return <h1>Counter: {count}</h1>
}
You want to update the count state to be count + 1 from inside the Effect. However, this makes your Effect depend on count, which changes with every tick, and that's why your interval gets re-created on every tick.
To solve this, use the updater function and write setCount(c => c + 1) instead of setCount(count + 1):
import { useState, useEffect } from 'react';
export default function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('✅ Creating an interval');
const id = setInterval(() => {
console.log('⏰ Interval tick');
setCount(c => c + 1);
}, 1000);
return () => {
console.log('❌ Clearing an interval');
clearInterval(id);
};
}, []);
return <h1>Counter: {count}</h1>
}
Instead of reading count inside the Effect, you pass a c => c + 1 instruction ("increment this number!") to React. React will apply it on the next render. And since you don't need to read the value of count inside your Effect anymore, you can keep your Effect's dependencies empty ([]). This prevents your Effect from re-creating the interval on every tick.
Fix a retriggering animation
In this example, when you press "Show", a welcome message fades in. The animation takes a second. When you press "Remove", the welcome message immediately disappears. The logic for the fade-in animation is implemented in the animation.js file as plain JavaScript animation loop. You don't need to change that logic. You can treat it as a third-party library. Your Effect creates an instance of FadeInAnimation for the DOM node, and then calls start(duration) or stop() to control the animation. The duration is controlled by a slider. Adjust the slider and see how the animation changes.
