title: Unable to stop memory leak in useEffect hook ,React JS
body: <p>I have a landing page in React with below function for changing image in carousel.</p>
  <p>After I navigate away, it gives error <code>'Can't perform a React state update on an unmounted component.'</code></p>
  <p>Below function change carousel image in every 2 second.</p>
  <pre><code>  // state to find idex
    const [imageIndex, setImageIndex] = React.useState(0); 
  
    //array of images to display
    const images =  [
    image1,image3,image2,
      ];
      
    //function that changes image index in every 2 second
    const nextImage = () =&gt; {
      setImageIndex((prev) =&gt; (prev + 1) % images.length);
      setTimeout(nextImage, 2000);
    };
  
    // function to initiate above function, the memory leak happens here
    React.useEffect(nextImage, []);
  </code></pre>
  <p>I have gone through some StackOverflow questions and changed my timing function as below but the error still exists,</p>
  <pre><code>// useEffect triggers this functions
  
  const nextImage = () =&gt; {
      let unmounted = false;
      if (!unmounted) {
        setImageIndex((prev) =&gt; (prev + 1) % images.length);
        setTimeout(nextImage, 2000);
      }
  
      return () =&gt; {
        unmounted = true;
      };
    };
  
  </code></pre>
  <p>Question I referred <a href="https://stackoverflow.com/a/58038029/10515390">https://stackoverflow.com/a/58038029/10515390</a> have answer but I did not get the clear  idea.</p>