According to the official React docs, it is recommended to use multiple useEffects to separate concerns instead of one. However, I am wondering if that means separating them for example by particular dependency or rather the side effects' logic itself. For example, let's take this useEffect:
useEffect(() => {
xyz()
foo();
if (instanceOfA(dependency)) {
bar();
}
if (instanceOfB(dependency)) {
const interval = setInterval(() => {
baz();
}, 1000);
return () => clearInterval(interval);
}
}, [dependency]);
Well, they are for sure grouped in this case and depended on the single dependency, but it feels like this useEffect is kind of all over the place.
If I was to refactor it, I would probably split it into smaller useEffects, for example something like this:
useEffect(() => {
foo()
xyz()
}, [dependency])
useEffect(() => {
if (instanceOfA(dependency)) {
bar()
}
}, [dependency])
useEffect(() => {
if (instanceOfB(dependency)) {
const interval = setInterval(() => {
baz()
}, 1000)
return () => clearInterval(interval)
}
}, [dependency])
I guess with this approach we have more control over e.g. clean up functions and if needed, all of those hooks could be exported to own custom hooks. On the downside, instead of a single useEffect, we now have 3 different effects to handle.
What would you say is a better pattern in terms of performance / architecture and why?