react: Feedback on useEffect depndencies change error
Some feedback on useEffect
What is the current behavior?
I am using useEffect to load details on a set of users that are kept in props.
I want to minimize loading and there are situations where the array of users (and the actual user objects) are recreated but really they refer to the same identities.
So I do
const userIds = users.map(u => id)
useEffect(() => {
if(!userIds.length)
return
...load more stuff by querying endpoints about these ids and set state..
}, userIds)
aand I run into a warning
The final argument passed to useEffect changed size between renders. The order and size of this array must remain constant
which to me is…kinda the point, is it not? I understand if we don’t want to do a deep comparison in the dependencies, but if the dependencies themselves change…well that seems straightforward, run the effect.
I know that I can do [userIds.join(' ']) in this case, but that seems like just extra work for no reason and really anti-intuitive. And ends up doing the same exact thing but with extra steps!
To be clear, what I’m proposing is removing this whole block here and replacing it with
if (nextDeps.length !== prevDeps.length)
return false
As far as I can tell, this warning serves no real purpose and makes the use case outlined above awkward to deal with
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 5
- Comments: 16
Anyway for your code, I feel there’s a more efficient way.
What could be better
Or if you don’t need to use variable userIds anywhere else
Yup - if you look at the code, it would seem that you can replace
with
and then my use case would be supported and there would be no other negative effects.
So I’m asking the team what is the purpose of this warning and also why not change it?
@universse that would trigger if the ids change length only? So if I add a thing and remove a thing, it will not fetch details.
But really, its not like I can’t figure out a way to hack around it - I have one above, its that I don’t understand why this limitation would be there in the first place, from looking at the code, absolutely nothing seems to depend on it, if you replaced it with what I propose above it would just work.