title: Can't update state when using `setFoo` as a callback for websocket `onmessage` event
body: <p><strong>Goal:</strong></p>
  
  <p>I'm trying to get messages from a server through a websocket connection and add them to an array of objects called <code>outgoingMessages</code>.</p>
  
  <p><strong>Problem:</strong> </p>
  
  <p>Only the newest message is saved in <code>outgoingMessages</code> when <code>receive()</code> is called.</p>
  
  <p>I suspect this happens because <code>Websocket.onmessage</code> only uses the value of <code>outgoingMessages</code> from the time when I call <code>connect()</code>. I've tried fiddling around with it quite a bit, but I haven't been able to fix this issue.</p>
  
  <p>How can I get <code>receive()</code> to use the current state, not the initial one?</p>
  
  <p>Thanks in advance.</p>
  
  <pre><code>const Dashboard = () =&gt; {
    const [incomingMessages, setIncomingMessages] = React.useState([]);
    const ws = React.useRef(null);
  
    const receive = (message) =&gt; {
      setIncomingMessages([...incomingMessages, message]);
    };
  
    const connect = () =&gt; {
      ws.current = new WebSocket(WS_URL + "mqtt/ws/messages");
      ws.current.onopen = () =&gt; setWsConnected(true);
      ws.current.onclose = () =&gt; setWsConnected(false);
      ws.current.onmessage = (event) =&gt; receive(event);
    };
  
    return (&lt;&gt;Stuff&lt;/&gt;)
  }
  </code></pre>