title: How to get the previous state in React functional component?
body: <p>I am writing a React component using hooks and I try to get the previous state of some variable, i.e, render the current and previous count in the Counter: <a href="https://codesandbox.io/s/upbeat-kilby-4jxni?file=/src/App.js" rel="nofollow noreferrer">CodeSandBox Example</a></p>
  <pre><code>function usePrevious(value) {
    const ref = useRef();
  
    useEffect(() =&gt; {
      ref.current = value;
    }, [value]); 
  
    return ref.current;
  }
  
  const Counter = () =&gt; {
    const [count, setCount] = useState(0)
    const prevCount = usePrevious(count)
    
    const [x,setX] = useState(0)
    
    return (
      &lt;div&gt;
        &lt;p&gt;count: {count}, prev count: {prevCount}&lt;/p&gt;
        &lt;button onClick={() =&gt; setCount(count + 1)}&gt;
          Add count
        &lt;/button&gt;
        &lt;button onClick={() =&gt; setX(x + 1)}&gt;
          Change x
        &lt;/button&gt;
      &lt;/div&gt;
    )
  }
  </code></pre>
  <p>When I click &quot;Add count&quot;, everything is ok.
  But if I click the &quot;Change X&quot; button, which triggers a re-render of the component, then I will get the current value of count but not the value before changing.</p>
  <p>So how can I get the correct previous count even if there is a re-render?</p>