Removing Effect Dependencies — Summary
Source: https://react.dev/learn/removing-effect-dependencies#to-change-the-dependencies-change-the-code
Key points of "To change the dependencies, change the code"
The dependency array isn't something you choose. It is determined by the Effect's code. If you want different dependencies, change the code, not the array.
The process has three steps:
- Change the Effect's code, or the way its values are declared.
- Follow the linter and update the dependency array to match the new code.
- If you're not satisfied, go back to step 1.
Suppressing the dependency warning with eslint-disable can cause bugs, because the Effect keeps using stale values.
To remove a dependency, you have to show the linter that the value isn't reactive. For example, if you move roomId outside the component as a constant, the dependency array can be empty.
Recipes from the rest of the page
| Situation | Fix |
|---|---|
| You're using an Effect to respond to a specific action, such as clicking a send button | Move the logic into an event handler |
| One Effect does two unrelated things | Split it into separate Effects |
| You read state only to compute the next state from the previous one | Use an updater function (msgs => [...msgs, msg]) |
| You want to read a value without re-running the Effect when it changes | Extract it into an Effect Event (useEffectEvent) |
| An object or function is recreated on every render | Move it outside the component, create it inside the Effect, or extract primitive values from it |
Objects and functions are different on every render, even when their contents are identical (Object.is returns false). Using them as dependencies makes the Effect re-run too often. To avoid this:
- Move static objects and functions outside the component.
- Create dynamic ones inside the Effect.
- Extract primitive values such as
roomIdandserverUrl, and depend on those instead.
Notes
- Treat linter warnings like compile errors.
- When you want fewer dependencies, review the code first, not the array.
