'Removing Effect Dependencies'·续1
```js {6-7} function Form() { const theme = useContext(ThemeContext);
function handleSubmit() { // ✅ Good: Event-specific logic is called from event handlers post('/api/register'); showNotification('Successfully registered!', theme); }
// ... }
Now that the code is in an event handler, it's not reactive--so it will only run when the user submits the form. Read more about [choosing between event handlers and Effects](/learn/separating-events-from-effects#reactive-values-and-reactive-logic) and [how to delete unnecessary Effects.](/learn/you-might-not-need-an-effect)
### Is your Effect doing several unrelated things?
The next question you should ask yourself is whether your Effect is doing several unrelated things.
Imagine you're creating a shipping form where the user needs to choose their city and area. You fetch the list of `cities` from the server according to the selected `country` to show them in a dropdown:
```js
function ShippingForm({ country }) {
const [cities, setCities] = useState(null);
const [city, setCity] = useState(null);
useEffect(() => {
let ignore = false;
fetch(`/api/cities?country=${country}`)
.then(response => response.json())
.then(json => {
if (!ignore) {
setCities(json);
}
});
return () => {
ignore = true;
};
}, [country]); // ✅ All dependencies declared
// ...
This is a good example of fetching data in an Effect. You are synchronizing the cities state with the network according to the country prop. You can't do this in an event handler because you need to fetch as soon as ShippingForm is displayed and whenever the country changes (no matter which interaction causes it).
Now let's say you're adding a second select box for city areas, which should fetch the areas for the currently selected city. You might start by adding a second fetch call for the list of areas inside the same Effect:
```js {15-24,28} function ShippingForm({ country }) { const [cities, setCities] = useState(null); const [city, setCity] = useState(null); const [areas, setAreas] = useState(null);
useEffect(() => {
let ignore = false;
fetch(/api/cities?country=${country})
.then(response => response.json())
.then(json => {
if (!ignore) {
setCities(json);
}
});
// 🔴 Avoid: A single Effect synchronizes two independent processes
if (city) {
fetch(/api/areas?city=${city})
.then(response => response.json())
.then(json => {
if (!ignore) {
setAreas(json);
}
});
}
return () => {
ignore = true;
};
}, [country, city]); // ✅ All dependencies declared
// ...
However, since the Effect now uses the `city` state variable, you've had to add `city` to the list of dependencies. That, in turn, introduced a problem: when the user selects a different city, the Effect will re-run and call `fetchCities(country)`. As a result, you will be unnecessarily refetching the list of cities many times.
**The problem with this code is that you're synchronizing two different unrelated things:**
1. You want to synchronize the `cities` state to the network based on the `country` prop.
1. You want to synchronize the `areas` state to the network based on the `city` state.
Split the logic into two Effects, each of which reacts to the prop that it needs to synchronize with:
```js {19-33}
function ShippingForm({ country }) {
const [cities, setCities] = useState(null);
useEffect(() => {
let ignore = false;
fetch(`/api/cities?country=${country}`)
.then(response => response.json())
.then(json => {
if (!ignore) {
setCities(json);
}
});
return () => {
ignore = true;
};
}, [country]); // ✅ All dependencies declared
const [city, setCity] = useState(null);
const [areas, setAreas] = useState(null);
useEffect(() => {
if (city) {
let ignore = false;
fetch(`/api/areas?city=${city}`)
.then(response => response.json())
.then(json => {
if (!ignore) {
setAreas(json);
}
});
return () => {
ignore = true;
};
}
}, [city]); // ✅ All dependencies declared
// ...
Now the first Effect only re-runs if the country changes, while the second Effect re-runs when the city changes. You've separated them by purpose: two different things are synchronized by two separate Effects. Two separate Effects have two separate dependency lists, so they won't trigger each other unintentionally.
The final code is longer than the original, but splitting these Effects is still correct. Each Effect should represent an independent synchronization process. In this example, deleting one Effect doesn't break the other Effect's logic. This means they synchronize different things, and it's good to split them up. If you're concerned about duplication, you can improve this code by extracting repetitive logic into a custom Hook.
Are you reading some state to calculate the next state?
This Effect updates the messages state variable with a newly created array every time a new message arrives:
```js {2,6-8} function ChatRoom({ roomId }) { const [messages, setMessages] = useState([]); useEffect(() => { const connection = createConnection(); connection.connect(); connection.on('message', (receivedMessage) => { setMessages([...messages, receivedMessage]); }); // ...
It uses the `messages` variable to [create a new array](/learn/updating-arrays-in-state) starting with all the existing messages and adds the new message at the end. However, since `messages` is a reactive value read by an Effect, it must be a dependency:
```js {7,10}
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
useEffect(() => {
const connection = createConnection();
connection.connect();
connection.on('message', (receivedMessage) => {
setMessages([...messages, receivedMessage]);
});
return () => connection.disconnect();
}, [roomId, messages]); // ✅ All dependencies declared
// ...
And making messages a dependency introduces a problem.
Every time you receive a message, setMessages() causes the component to re-render with a new messages array that includes the received message. However, since this Effect now depends on messages, this will also re-synchronize the Effect. So every new message will make the chat re-connect. The user would not like that!
To fix the issue, don't read messages inside the Effect. Instead, pass an updater function to setMessages:
```js {7,10} function ChatRoom({ roomId }) { const [messages, setMessages] = useState([]); useEffect(() => { const connection = createConnection(); connection.connect(); connection.on('message', (receivedMessage) => { setMessages(msgs => [...msgs, receivedMessage]); }); return () => connection.disconnect(); }, [roomId]); // ✅ All dependencies declared // ...
**Notice how your Effect does not read the `messages` variable at all now.** You only need to pass an updater function like `msgs => [...msgs, receivedMessage]`. React [puts your updater function in a queue](/learn/queueing-a-series-of-state-updates) and will provide the `msgs` argument to it during the next render. This is why the Effect itself doesn't need to depend on `messages` anymore. As a result of this fix, receiving a chat message will no longer make the chat re-connect.
### Do you want to read a value without "reacting" to its changes?
Suppose that you want to play a sound when the user receives a new message unless `isMuted` is `true`:
```js {3,10-12}
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
const [isMuted, setIsMuted] = useState(false);
useEffect(() => {
const connection = createConnection();
connection.connect();
connection.on('message', (receivedMessage) => {
setMessages(msgs => [...msgs, receivedMessage]);
if (!isMuted) {
playSound();
}
});
// ...
Since your Effect now uses isMuted in its code, you have to add it to the dependencies:
```js {10,15} function ChatRoom({ roomId }) { const [messages, setMessages] = useState([]); const [isMuted, setIsMuted] = useState(false);
useEffect(() => { const connection = createConnection(); connection.connect(); connection.on('message', (receivedMessage) => { setMessages(msgs => [...msgs, receivedMessage]); if (!isMuted) { playSound(); } }); return () => connection.disconnect(); }, [roomId, isMuted]); // ✅ All dependencies declared // ...
The problem is that every time `isMuted` changes (for example, when the user presses the "Muted" toggle), the Effect will re-synchronize, and reconnect to the chat. This is not the desired user experience! (In this example, even disabling the linter would not work--if you do that, `isMuted` would get "stuck" with its old value.)
To solve this problem, you need to extract the logic that shouldn't be reactive out of the Effect. You don't want this Effect to "react" to the changes in `isMuted`. [Move this non-reactive piece of logic into an Effect Event:](/learn/separating-events-from-effects#declaring-an-effect-event)
```js {1,7-12,18,21}
import { useState, useEffect, useEffectEvent } from 'react';
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
const [isMuted, setIsMuted] = useState(false);
const onMessage = useEffectEvent(receivedMessage => {
setMessages(msgs => [...msgs, receivedMessage]);
if (!isMuted) {
playSound();
}
});
useEffect(() => {
const connection = createConnection();
connection.connect();
connection.on('message', (receivedMessage) => {
onMessage(receivedMessage);
});
return () => connection.disconnect();
}, [roomId]); // ✅ All dependencies declared
// ...
Effect Events let you split an Effect into reactive parts (which should "react" to reactive values like roomId and their changes) and non-reactive parts (which only read their latest values, like onMessage reads isMuted). Now that you read isMuted inside an Effect Event, it doesn't need to be a dependency of your Effect. As a result, the chat won't re-connect when you toggle the "Muted" setting on and off, solving the original issue!
Wrapping an event handler from the props
You might run into a similar problem when your component receives an event handler as a prop:
```js {1,8,11} function ChatRoom({ roomId, onReceiveMessage }) { const [messages, setMessages] = useState([]);
useEffect(() => { const connection = createConnection(); connection.connect(); connection.on('message', (receivedMessage) => { onReceiveMessage(receivedMessage); }); return () => connection.disconnect(); }, [roomId, onReceiveMessage]); // ✅ All dependencies declared // ...
Suppose that the parent component passes a *different* `onReceiveMessage` function on every render:
```js {3-5}
<ChatRoom
roomId={roomId}
onReceiveMessage={receivedMessage => {
// ...
}}
/>
Since onReceiveMessage is a dependency, it would cause the Effect to re-synchronize after every parent re-render. This would make it re-connect to the chat. To solve this, wrap the call in an Effect Event:
```js {4-6,12,15} function ChatRoom({ roomId, onReceiveMessage }) { const [messages, setMessages] = useState([]);
const onMessage = useEffectEvent(receivedMessage => { onReceiveMessage(receivedMessage); });
useEffect(() => { const connection = createConnection(); connection.connect(); connection.on('message', (receivedMessage) => { onMessage(receivedMessage); }); return () => connection.disconnect(); }, [roomId]); // ✅ All dependencies declared // ...
Effect Events aren't reactive, so you don't need to specify them as dependencies. As a result, the chat will no longer re-connect even if the parent component passes a function that's different on every re-render.
#### Separating reactive and non-reactive code
In this example, you want to log a visit every time `roomId` changes. You want to include the current `notificationCount` with every log, but you *don't* want a change to `notificationCount` to trigger a log event.
The solution is again to split out the non-reactive code into an Effect Event:
```js {2-4,7}
function Chat({ roomId, notificationCount }) {
const onVisit = useEffectEvent(visitedRoomId => {
logVisit(visitedRoomId, notificationCount);
});
useEffect(() => {
onVisit(roomId);
}, [roomId]); // ✅ All dependencies declared
// ...
}
You want your logic to be reactive with regards to roomId, so you read roomId inside of your Effect. However, you don't want a change to notificationCount to log an extra visit, so you read notificationCount inside of the Effect Event. Learn more about reading the latest props and state from Effects using Effect Events.
Does some reactive value change unintentionally?
Sometimes, you do want your Effect to "react" to a certain value, but that value changes more often than you'd like--and might not reflect any actual change from the user's perspective. For example, let's say that you create an options object in the body of your component, and then read that object from inside of your Effect:
```js {3-6,9} function ChatRoom({ roomId }) { // ... const options = { serverUrl: serverUrl, roomId: roomId };
useEffect(() => { const connection = createConnection(options); connection.connect(); // ...
This object is declared in the component body, so it's a [reactive value.](/learn/lifecycle-of-reactive-effects#effects-react-to-reactive-values) When you read a reactive value like this inside an Effect, you declare it as a dependency. This ensures your Effect "reacts" to its changes:
```js {3,6}
// ...
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]); // ✅ All dependencies declared
// ...
It is important to declare it as a dependency! This ensures, for example, that if the roomId changes, your Effect will re-connect to the chat with the new options. However, there is also a problem with the code above. To see it, try typing into the input in the sandbox below, and watch what happens in the console:
