Search code examples
javascriptreactjsreact-hooksreturn

Are there pitfalls with return value from cleanup function in useEffect of React 16+?


React documentation contains code samples with the cleanup function with curly braces without return and written on one line:

  1. with curly braces and omitted return
useEffect(() => {
  // setup function code
 
  // cleanup function code
  return () => {
    connection.disconnect();
  }
}, []);
  1. with curly braces omitted and without return
useEffect(() => {
  // setup function code
 
  // cleanup function code
  return () => connection.disconnect();
}, []);

In Theo mock-interview where was Dan Abramov as Interviewee, at 23:20 min (https://youtu.be/uqII0AOW1NM?t=1400) said he had a problem with no returning undefined from the cleanup function. Again: I reread the doc and couldn't find any mention of this.

And here I have a dilemma: how to write the reset functions correctly at the moment?


Solution

  • At the time useEffect typings was like this (it is now too) - just for ux.

    Now explicitly the type must be void. You can open typings in your editor (you can go from anywhere you useEffect)

    useEffect typing1 useEffect typing2 useEffect typing3

    When authors of libraries write void - it usually indicates that the result of the callback function will not be used in any way.

    In experience, if useEffect is asynchronous and relies on promis, direct writing without curly braces won't work here (similar example from https://javascript.plainenglish.io/commons-mistakes-with-react-useeffect-hook-and-how-to-prevent-them-d0ca253fb1f7).

    The authors of typings additionally threw in protections against something being returned (to protect against a Promise return, for example).

    They did it in general more for a good purpose - to improve DX, to keep it out of trouble and some unexpected behaviour

    For the react itself, it probably doesn't matter. You could even check: inside throw out the exceptions and look at the stacktrace, for example, so come out to the place where Destructor is called.

    All the typings for the reactor can be seen in the sources https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts. If anything, the types are not created by the authors of React itself.