0

I've learned that to prevent memory leaks, I'm supposed to clean up after useEffect hooks which call async functions to update state.

I have found a couple of solutions for this;

First one, to use a simple, boolean variable:

useEffect(() => {
let isSubscribed = true;

const runEffect = async () => {
  const data = await getSomething();
  isSubscribed && setState(data)
};

runEffect();

return () => {
      isSubscribed = false;
    };
  }, []);

And this method using the useRef hook:

const _isMounted = useRef(true); 

  useEffect(() => {
const runEffect = async () => {
      const data = await getSomething();
      _isMounted.current && setState(data)
    };

    runEffect();

    return () => { 
        _isMounted.current = false;
    }
  }, []);

Is there a big enough difference between the two methods? If so, which is better?

ibrahim
  • 182
  • 3
  • 11
  • Both examples are useless because the variable not doing anything, can you give a practical example? The cleanup effect in those examples runs when the component unmounts, how they cleaning something? – Dennis Vash Sep 11 '20 at 15:05
  • You should read this question: https://stackoverflow.com/questions/57444154/why-need-useref-to-contain-mutable-variable-but-not-define-variable-outside-the/57444430#57444430 about `useRef` vs Variables – Dennis Vash Sep 11 '20 at 15:07
  • Moreover you **SHOULDN'T** use a reference in cleaning function, you even get a warning for that, try it. – Dennis Vash Sep 11 '20 at 15:09
  • @DennisVash thank you for the reply. From my understanding, the returned anonymous function ensures that a state update doesn't happen when that component unmounts. Have I got it wrong? – ibrahim Sep 11 '20 at 15:28
  • You can't make state update when component unmounts, you don't have a state, it doesn't need to ensure anything. The cleanup function is just a callback. – Dennis Vash Sep 11 '20 at 15:33
  • Well I've been using the boolean variable method, and that's solved the React warning about memory leaks. – ibrahim Sep 11 '20 at 15:37

0 Answers0