title: How to clean up setInterval in useEffect using react hooks
body: <p>I am trying to create a loading component that will add a period to a div periodically, every 1000ms using setInterval in React. I am trying to cleanup setInterval using the method described in the docs. </p>
  
  <p><a href="https://reactjs.org/docs/hooks-effect.html#example-using-hooks-1" rel="noreferrer">https://reactjs.org/docs/hooks-effect.html#example-using-hooks-1</a></p>
  
  <pre><code>import React, { useEffect, useState } from 'react'
  
  const Loading = () =&gt; {
      const [loadingStatus, setLoadingStatus] = useState('.')
      const [loop, setLoop] = useState()
      useEffect(() =&gt; {
          setLoop(setInterval(() =&gt; {
              console.log("loading")
              setLoadingStatus(loadingStatus + ".")
          }, 1000))
  
          return function cleanup() {
              console.log('cleaning up')
              clearInterval(loop)
          }
      }, [])
      return (&lt;p&gt;
          {`Loading ${loadingStatus}`}
      &lt;/p&gt;)
  }
  export default Loading
  </code></pre>
  
  <p>However , the loadingStatus variable only updates once and the setInterval loop doesnt get cleared even after the component stops mounting. Do I have to make this using a class component?</p>