Eliminate redundant dependencies in React's useEffect
P粉333395496
P粉333395496 2024-04-01 13:43:57
0
1
456

I have a useEffect which has two dependencies:

useEffect(() => {
   doSomething();
}, [currentTenant, currentProjects])

However, currentProjects is being set in useEffect, which has currentTenant as a dependency:

useEffect(() => {
   setCurrentProjects();
}, [currentTenant]);

doSomething() depends on these two states, so I'm wondering if doSomething() will run twice when currentTenant changes: once when currentTenant itself changes, and once when currentProjects (controlled by currentTenant ) changes. < /p>

Is this redundant? What's a better way to do this? Maybe by removing currentTenant from doSomething() useEffect .

Thanks in advance for your help.

P粉333395496
P粉333395496

reply all(1)
P粉291886842

I think you're making things error-prone and unnecessarily complicated. In my experience, whenever people. Trying to use useEffect smartly, they just broke it.

First, make sure currentTenant and currentProjects are primitives - I guess that's not the case yet (e.g. something named currentProjects), so your dependencies The item will not work as expected anyway.

Second, if possible, inline the code for doSomething() and setCurrentProjects() so it's easier to keep track of which variables/dependencies you actually rely on. Exceptions exist if you have passed these methods to a component or used them in multiple places.

Third, do not rely on the order in which multiple useEffect hooks are called. There is no ordering guaranteed in the documentation, and it doesn't make much sense for asynchronous calls. Make them independent of each other. Therefore, do not assume redundancy without certainty. Furthermore, even if it works as expected, this is a premature optimization - the benefit is negligible, but the code is harder to understand.

Fourth, you are relying on the imagination that nothing will change in your components, and your future self, as well as your colleagues, will know/remember exactly your dependency considerations. Or you have to comment on it with lengthy explanations that make the idea more complex.

In general, useEffect dependencies should be as simple and expressive as possible. They don't have a lot of magic, but they have a lot of people. Still (me included) screw them up sometimes. This happens when you mostly deviate from the "just list all primitives you are using" rule.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template