I was debating with a collegue today about using the “return
” key in a useEffect
to stop code execution. I have learned that using return
should only be done in a cleanup.
The issue:
useEffect(() => { if (stateCondition) { //do fancy stuff return; } // more code to execute if condition is not met }, [props]);
The way I see this is that we should perhaps have yet another useEffect
that only execute if the state is false and not use the “return
” as above.
I am trying to find some documentation to support my claim but so far I have not been able to.
What I am looking for:
Am I right here? is there documentation that supports my claim or the other way arround?
Advertisement
Answer
Technically it doesn’t really make a difference in this case. Because return;
explicitly returns undefined
, which is already implicitly returned by any JavaScript function which doesn’t return anything.
The React framework knows not to execute an undefined
cleanup function, so no harm is done.
Returning anything else from a useEffect
function other than a cleanup function or undefined
could potentially cause bugs. You could test it if you want, but it’s kind of a moot point and nothing more than a passing curiosity, since you simply shouldn’t do it as cleaning up from useEffect
is documented to happen from returning a function.
As an opinion, I would recommend never using return
in any useEffect
unless it’s explicitly a cleanup function. Even if no harm is done in this particular case, another developer who happens upon this pattern may not know that and may get confused about returning from an effect.
For this particular case, it seems a simple else
block would produce the same logic.