Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it valid to use the "return" keyword in a useEffect to stop code execution?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading