title: React Hooks Sending message at first in Websockets
body: <p>I can't send message after subsequential clicks, if i click button at first time it is sending message to server, after that it is not sending messages to server.</p>
  <pre><code>import { useEffect, useState, useRef } from &quot;react&quot;;
  
  import Header from &quot;../src/Components/Header&quot;;
  import ChatHistory from &quot;../src/Components/ChatHistory&quot;;
  import ChatArea from &quot;../src/Components/ChatArea&quot;;
  
  function App() {
    const [messages, setMessages] = useState([]);
  
    const testValue = { messages, setMessages };
  
    const socket = useRef(null);
  
    const renderCount = useRef(0);
  
    const sendMessage = (msg = &quot;test&quot;) =&gt; {
      if (socket.current) {
        socket.current.send(msg);
      }
      addMessages(msg);
    };
  
    const addMessages = (msg) =&gt; {
      setMessages((prev) =&gt; [...prev, msg]);
    };
  
    useEffect(() =&gt; {
      socket.current = new WebSocket(&quot;ws://localhost:8001/ws&quot;);
      socket.current.onmessage = (msg) =&gt; {
        addMessages(msg);
      };
    }, []);
  
    useEffect(() =&gt; {
      return () =&gt; {
        if (socket.current) {
          socket.current.close();
        }
      };
    }, [socket]);
  
    console.log(&quot;i am rendering&quot;);
  
    return (
      &lt;&gt;
        &lt;Header /&gt;
        &lt;ChatHistory chatHistory={messages.current} /&gt;
        &lt;div&gt;
          &lt;button onClick={sendMessage}&gt;Send&lt;/button&gt;
        &lt;/div&gt;
      &lt;/&gt;
    );
  }
  
  export default App;
  </code></pre>
  <p>Above mentioned one is my code, While clicking send button at first time, it is triggering message to server, after another subsequential clicks it isn't triggering message to server. Help needed.</p>