0

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?

CodingLittle
  • 1,761
  • 2
  • 17
  • 44
  • There's not really any problem with that code or the general idea of returning early in `useEffect()`. – Aurast Jan 03 '23 at 20:13
  • I don't know if it satisfies you, but [according to the types](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/4aa9de6b65ff34a5fc453bb07719e7f6dab8f039/types/react/v17/index.d.ts#L1083) there's nothing wrong with it. I have to believe if they didn't want you to do it, there would be a type rule or lint rule that prevents it (a la the lint rule against returning a Promise or supplying an async callback works). – Jared Smith Jan 03 '23 at 20:14
  • @Aurast the thing is that the return in this case is not cleaning anything it is just stoping it from executing more code, that why I thought it would be wrong – CodingLittle Jan 03 '23 at 20:14
  • @DreamBold Not really, supports my claim that "return" is used in a cleanup but it does not say that I can not use "return" like above example to stop code execution. – CodingLittle Jan 03 '23 at 20:16
  • https://stackoverflow.com/questions/59384281/how-exactly-does-useeffects-return-work-why-is-the-code-preforming-like-it-doe – DreamBold Jan 03 '23 at 20:19

1 Answers1

5

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.

David
  • 208,112
  • 36
  • 198
  • 279