title: Problem with Websocket .send() in Reactjs
body: <p>I'm pretty new to react so sorry if the solution is obvious.
  For my project, I need to connect to a websocket inside a Component with the following code</p>
  
  <pre><code>let id = 2;
  
  const Dashboard = () =&gt; {
    const [apiOutput, setApiOutput] = useState([]);
    const [apiConnectionStatus, setApiConnectionStatus] = useState(false);
  
    const ws = new WebSocket("ws://XXXXXXX/api/websocket");
    const initWebsocket = () =&gt; {
      ws.addEventListener("open", () =&gt; {
        ws.send('{"type":"auth", "api_password":"XXXX"}');
        ws.send('{"id": 1, "type": "get_states"}');
        ws.send(
          '{"id": 2, "type": "subscribe_events", "event_type": "state_changed"}'
        );
      });
  
      ws.onopen = () =&gt; {
        setApiConnectionStatus(true);
      };
  
      ws.onmessage = evt =&gt; {
        const message = JSON.parse(evt.data);
        setApiOutput(message);
      };
  
      ws.onclose = error =&gt; {
        console.log(error);
        setApiConnectionStatus(false);
      };
    };
  
    useEffect(() =&gt; {
      initWebsocket();
    }, []);
  
    const switchHandler = entity_id =&gt; {
      console.log("switch =" + ws.readyState);
      id++;
      const command = `{"id": ${id}, "type": "call_service", "domain": "switch", "service": "toggle", "service_data": { "entity_id": "${entity_id}"}}`;
      ws.send(command);
    };
  </code></pre>
  
  <p>The <code>SwitchHandler</code> function is sent to a child Component via props and triggers as expected.
  The <code>apiOutput</code> State works as expected as well.</p>
  
  <p>The problem is that <code>ws.send(command)</code> is not working (like not triggering) even though <code>ws.readyState</code> returns 1 inside the <code>SwitchHandler</code> function.</p>
  
  <p>Is there anything obvious that I'm missing ?</p>