title: React: useState - Value is not correct in if statement
body: <p>I have a problem with useState in React. I want to query the current value of a state when a key is pressed, for key navigatgion. However, the console.log already always returns only the value &quot;1&quot;, which actually does not correspond to the current state.</p>
  <p>In useEffect, however, the state is always output correctly.  The problem is not the useEffect. It's the function &quot;checkKey&quot;. Here, the console.log(currentPage) always returns &quot;1&quot; which can not be the case.</p>
  <pre><code>  const [currentPage, setCurrentPage] = state(1);
    const [quotes, setQuotes] = state([&quot;fetching ...&quot;]);
    
    const checkKey = (event) =&gt; {
      if (event.keyCode == '37') {
          console.log(&quot;Key page:&quot; + currentPage); // Always 1???
          if(currentPage &gt; 1) setCurrentPage(currentPage =&gt; currentPage - 1);
      } else if (event.keyCode == '39') {
        console.log(&quot;Key page:&quot; + currentPage);
          if(currentPage &lt; 6) setCurrentPage(currentPage =&gt; currentPage + 1);
      }
    }
  </code></pre>
  <p>With useEffect (changed slightly here with a custom hook, but the functionality is identical, the return value is always correct) the issue does not occur. The navigation is generally working fine, and after each update, the console.log here outputs the correct value.</p>
  <pre><code>  /*currentPage */ onChange(() =&gt; {
      if (currentPage === 1) {
        navigateTo('/');
      }
      if (currentPage === 2) {
        navigateTo('/resume');
      }
      if (currentPage === 3) {
        navigateTo('/certificates');
      }
      if (currentPage === 4) {
        navigateTo('/project-cdp');
      }
      if (currentPage === 5) {
        navigateTo('/lor-webedia');
      }
      console.log(&quot;New page is: &quot; + currentPage);
    }, [currentPage])
  </code></pre>
  <p>FYI: useEffect Custom Hook.</p>
  <pre><code>export const useEffectExceptOnMount = (effect, dependencies) =&gt; {
      const mounted = useRef(false);
      useEffect(() =&gt; {
        if (mounted.current) {
          const unmount = effect();
          return () =&gt; unmount &amp;&amp; unmount();
        } else {
          mounted.current = true;
        }
      }, dependencies);
    
      // Reset on unmount for the next mount.
      useEffect(() =&gt; {
        return () =&gt; mounted.current = false;
      }, []);
    };
  </code></pre>