title: How to fix closure in react when using addEventListener and useState
body: <p>I've made a simple example of a counter and want to console log value on mouse click, but it always displays 0. How can fix it?</p>
  <pre><code>import &quot;./App.css&quot;;
  import { useState } from &quot;react&quot;;
  import { useEffect } from &quot;react&quot;;
  
  function App() {
    const [num, setNum] = useState(0);
  
    const handler = () =&gt; {
      console.log(num);
    };
  
    useEffect(() =&gt; {
      window.addEventListener(&quot;click&quot;, handler);
    }, []);
  
    return (
      &lt;div className=&quot;App&quot;&gt;
        &lt;header className=&quot;App-header&quot;&gt;
          &lt;div
            onClick={() =&gt; {
              setNum(num + 1);
            }}
          &gt;
            Add
          &lt;/div&gt;
          &lt;h1&gt;{num}&lt;/h1&gt;
        &lt;/header&gt;
      &lt;/div&gt;
    );
  }
  
  export default App;
  
  </code></pre>
  <p><img src="https://i.stack.imgur.com/7TjTs.png" alt="image" /></p>