using local var for out of order operation in useEffect

  useEffect(() => {
    let ignore = false;    
    async function fetchProduct() {
      const response = await fetch('http://myapi/product/' + productId);
      const json = await response.json();
      if (!ignore) setProduct(json);    }

    fetchProduct();
    return () => { ignore = true };  }
, [productId]);

The above snippet is from https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops

I am not able to understand what is the purpose of the the last line return ()=> {ignore=true}. What is the effect of this statement, does it set the local variable true as true ? How does the ignore ever become true, because its set to false, and on next render it ill be again false ?

Answer

The function returned by useEffect is for cleanup. It’s an equivalend of componentWillUnmount in class components. React hooks docs

So overall: what happens in the hook is that the resource is fetched asynchronously. It may happen that it will finish fetching after the component is no longer on the screen. In this case it should be ignored. The cleaning runction set’s ignore to true and when the asynchronous part is finally executed the setProduct will not be executed.