title: useState React hook always returning initial value
body: <p>locationHistory is always an empty array in the following code:</p>
  
  <pre><code>export function LocationHistoryProvider({ history, children }) {
    const [locationHistory, setLocationHistory] = useState([])
  
    useEffect(() =&gt; history.listen((location, action) =&gt; {
      console.log('old state:', locationHistory)
      const newLocationHistory = locationHistory ? [...locationHistory, location.pathname] : [location.pathname]
      setLocationHistory(newLocationHistory)
    }), [history])
  
    return &lt;LocationHistoryContext.Provider value={locationHistory}&gt;{children}&lt;/LocationHistoryContext.Provider&gt;
  }
  </code></pre>
  
  <p><code>console.log</code> always logs <code>[]</code>. I have tried doing exactly the same thing in a regular react class and it works fine, which leads me to think I am using hooks wrong.</p>
  
  <p>Any advice would be much appreciated.</p>
  
  <p>UPDATE: Removing the second argument to <code>useEffect</code> (<code>[history]</code>) fixes it. But why? The intention is that this effect will not need to be rerun on every rerender. Becuase it shouldn't need to be. I thought that was the way effects worked.</p>
  
  <p>Adding an empty array also breaks it. It seems <code>[locationHistory]</code> must be added as the 2nd argument to <code>useEffect</code> which stops it from breaking (or no 2nd argument at all). But I am confused why this stops it from breaking? <code>history.listen</code> should run any time the location changes. Why does <code>useEffect</code> need to run again every time <code>locationHistory</code> changes, in order to avoid the aforementioned problem?</p>
  
  <p>P.S. Play around with it here: <a href="https://codesandbox.io/s/react-router-ur4d3?fontsize=14" rel="nofollow noreferrer">https://codesandbox.io/s/react-router-ur4d3?fontsize=14</a>  (thanks to lissitz for doing most the leg work there)</p>