title: Why is the cleanup function from `useEffect` called on every render?
body: <p>I've been learning React and I read that the function returned from <code>useEffect</code> is meant to do cleanup and React performs the cleanup when the component unmounts.</p>
  
  <p>So I experimented with it a bit but found in the following example that the function was called every time the component re-renders as opposed to only the time it got unmounted from the DOM, i.e. it <code>console.log("unmount");</code> every time the component re-renders.</p>
  
  <p>Why is that?</p>
  
  <pre><code>function Something({ setShow }) {
    const [array, setArray] = useState([]);
    const myRef = useRef(null);
  
    useEffect(() =&gt; {
      const id = setInterval(() =&gt; {
        setArray(array.concat("hello"));
      }, 3000);
      myRef.current = id;
      return () =&gt; {
        console.log("unmount");
        clearInterval(myRef.current);
      };
    }, [array]);
  
    const unmount = () =&gt; {
      setShow(false);
    };
  
    return (
      &lt;div&gt;
        {array.map((item, index) =&gt; {
          return (
            &lt;p key={index}&gt;
              {Array(index + 1)
                .fill(item)
                .join("")}
            &lt;/p&gt;
          );
        })}
        &lt;button onClick={() =&gt; unmount()}&gt;close&lt;/button&gt;
      &lt;/div&gt;
    );
  }
  
  function App() {
    const [show, setShow] = useState(true);
  
    return show ? &lt;Something setShow={setShow} /&gt; : null;
  }
  </code></pre>
  
  <p>Live example: <a href="https://codesandbox.io/s/vigilant-leavitt-z1jd2" rel="noreferrer">https://codesandbox.io/s/vigilant-leavitt-z1jd2</a></p>