title: Socket.io/React Chat App - Connection established
body: <p>i have two components:  where I set the username and room and then I have the  component where is the send message and displays the conversation.</p>
  <p>When I login on the  component, I navigate to the  component and trigger the connection with the socket:</p>
  <pre><code>const handleClick = (e) =&gt; {
      e.preventDefault();
      navigate(&quot;/chatroom&quot;, { state: { username, room } });
    };
  </code></pre>
  <p>I have two issues regarding the connection with the socket:</p>
  <p>-I´ve tried to start the connection inside an useEffect():</p>
  <pre><code>export default function ChatRoom() {
    const [chatMessage, setChatMessage] = useState(&quot;&quot;);
    const [showmsg, setShowMsg] = useState([]);
    const [showObj, setShowObj] = useState([]);
    const [submited, setSubmited] = useState(false);
  
  
  const handleSubmit = (e) =&gt; {
      e.preventDefault();
  
      setShowMsg((oldmsg) =&gt; [...oldmsg, chatMessage]);
      setChatMessage(&quot;&quot;);
      setSubmited(true);
    };
  
    const { state } = useLocation(); //to get data from &lt;Home/&gt; component
      useEffect(() =&gt; {
      const socket = io(&quot;http://localhost:3000&quot;);
      //Message from server
      socket.on(&quot;message&quot;, (msg) =&gt; {
        setShowObj((oldmsg) =&gt; [...oldmsg, msg]);
        setSubmited(false);
        console.log(showObj);
      });
  
      //Message to server
      socket.emit(&quot;chatMessage&quot;, {
        user: state.username,
        text: showmsg[showmsg.length - 1],
      }); //pass the last msg
    }, [submited]);
  </code></pre>
  <p>ServerSide:</p>
  <pre><code>io.on(&quot;connection&quot;, (socket) =&gt; {
    //Welcome current user
    socket.emit(&quot;message&quot;, formatMessage(&quot;MiouriChat&quot;, &quot;Welcome to the chat!&quot;));
  
    //Broadcast when user connects
    socket.broadcast.emit(
      &quot;message&quot;,
      formatMessage(&quot;MiouriChat&quot;, &quot;A user has joined the chat&quot;)
    );
  
    //Run when clients disconects
    socket.on(&quot;disconnect&quot;, () =&gt; {
      io.emit(&quot;message&quot;, formatMessage(&quot;MiouriChat&quot;, &quot;A user has left the chat&quot;));
    });
  
    //Listen to chat message from client
    socket.on(&quot;chatMessage&quot;, (msg) =&gt; {
      io.emit(&quot;message&quot;, formatMessage(msg.user, msg.text));
    });
  });
  </code></pre>
  <p>This way, everytime I submit a msg ([submited] change), the connection is reseted for obvious reason and get the &quot;welcome&quot; messages everytime it reconects.</p>
  <p>If I put the connection outside the useEffect(), the connection reseted everytyme I type a letter on the message input (becouse the state updates.)</p>
  <p>What is the best solution for this?</p>