title: Referencing outdated state in React useEffect hook
body: <p>I want to save state to <code>localStorage</code> when a component is unmounted.
  This used to work in <code>componentWillUnmount</code>.</p>
  
  <p>I tried to do the same with the <code>useEffect</code> hook, but it seems state is not correct in the return function of <code>useEffect</code>.</p>
  
  <p>Why is that? How can I save state without using a class?</p>
  
  <p>Here is a dummy example. When you press close, the result is always 0.</p>
  
  <pre class="lang-js prettyprint-override"><code>import React, { useState, useEffect } from "react";
  import ReactDOM from "react-dom";
  
  function Example() {
    const [tab, setTab] = useState(0);
    return (
      &lt;div&gt;
        {tab === 0 &amp;&amp; &lt;Content onClose={() =&gt; setTab(1)} /&gt;}
        {tab === 1 &amp;&amp; &lt;div&gt;Why is count in console always 0 ?&lt;/div&gt;}
      &lt;/div&gt;
    );
  }
  
  function Content(props) {
    const [count, setCount] = useState(0);
  
    useEffect(() =&gt; {
      // TODO: Load state from localStorage on mount
  
      return () =&gt; {
        console.log("count:", count);
      };
    }, []);
  
    return (
      &lt;div&gt;
        &lt;p&gt;Day: {count}&lt;/p&gt;
        &lt;button onClick={() =&gt; setCount(count - 1)}&gt;-1&lt;/button&gt;
        &lt;button onClick={() =&gt; setCount(count + 1)}&gt;+1&lt;/button&gt;
        &lt;button onClick={() =&gt; props.onClose()}&gt;close&lt;/button&gt;
      &lt;/div&gt;
    );
  }
  
  ReactDOM.render(&lt;Example /&gt;, document.querySelector("#app"));
  </code></pre>
  
  <p><a href="https://codesandbox.io/s/l5zjyyk87" rel="noreferrer">CodeSandbox</a></p>