Removing Effect Dependencies (React Docs Summary)
Source: https://react.dev/learn/removing-effect-dependencies
Core Idea
An Effect's dependency list must match the reactive values its code reads (props, state, and anything declared in the component body). You don't choose the dependencies; the code determines them. To change the dependencies, change the code. Suppressing the linter leads to stale values, so treat the dependency lint error like a compile error.
Is Your Effect Doing Several Unrelated Things?
- Rule: An Effect should represent one independent synchronization process. If it synchronizes unrelated things, split it into separate Effects, each with its own dependency list.
-
Example: A
ShippingFormfetchescitiesbased oncountryandareasbased oncityin one Effect with[country, city]as dependencies. Changing the city re-runs the Effect and needlessly refetches the cities. -
Fix: Use two Effects: the cities fetch depends on
[country], and the areas fetch depends on[city]. - Trade-off: The code gets longer, but splitting is still correct, and deleting one Effect no longer breaks the other. If the duplication bothers you, extract the shared logic into a custom Hook.
Other Ways to Remove an Unnecessary Dependency
- Move the code to an event handler. Code that runs because of a specific user interaction belongs in an event handler, not an Effect. Event handlers aren't reactive, so they run only on submit.
-
Use an updater function.
setMessages(msgs => [...msgs, receivedMessage])means the Effect no longer readsmessages. -
Read a value without reacting to it. Move the non-reactive logic into an Effect Event (
useEffectEvent). Effect Events always read the latest values and aren't dependencies. For example, togglingisMutedno longer reconnects the chat. -
Avoid unintentionally changing values. Objects and functions created during render are new values on every render. In order of preference:
- Move static objects or functions outside the component.
- Create dynamic objects or functions inside the Effect.
- Use primitive values extracted from objects as dependencies.
- Wrap event-handler props in an Effect Event.
Recap
- Dependencies must match the code; change the code to change them.
- Never suppress the linter.
- Use event handlers for interaction-specific logic.
- Split Effects that synchronize unrelated things.
- Use updater functions and Effect Events for values you only need to read.
- Avoid object and function dependencies.
The page ends with four challenges: a resetting interval, a retriggering animation, and two reconnecting chats.
Top comments (0)