title: Accessing my socket variable outside of useEffect
body: <p>I am using socket.io for multiple chat rooms, and want my socket connection to exist only when the chatroom is open, and close when the chatroom is unmounted. Currently, I connect to my socket in my useEffect hook. The problem is, I can't do socket.emit() in any of my functions because my socket is defined in useEffect like so:</p>
  
  <pre><code>import io from 'socket.io-client'
  
  export default function Chat() {
    useEffect(() =&gt; {
      const socket = io(endpoint + '/chat')
      return () =&gt; { socket.disconnect() }
    }
  
    const sendMessage = (msg) =&gt; {
      // Cant access this because socket is defined in useEffect!
      socket.emit('message', msg)
    }
  }
  </code></pre>
  
  <p>I have tried declaring my socket right under my import like so:</p>
  
  <pre><code>import io from 'socket.io-client'
  const socket = io(endpoint + '/chat')
  
  export default function Chat() {
  ...
  }
  </code></pre>
  
  <p>However, the problem with this way is that the 
  <code>socket.disconnect()</code>
  inside the useEffect hook doesn't work anymore, and the socket connection stays alive.</p>
  
  <p>I have also tried declaring my socket as a variable of my function like so:</p>
  
  <pre><code>export default function Chat() {
    const socket = io (endpoint + '/chat')
     ...
  }
  </code></pre>
  
  <p>but this will cause multiple socket connections to fire, and I end up getting memory leaks and many, many socket connections on my server which can't all be closed with socket.disconnect()</p>
  
  <p>Any help would be greatly appreciated, thanks</p>