title: How to update Socket.io handlers without re-connecting in React
body: <p>I have a <strong>react native</strong> project that uses <strong>socket.io</strong> to communicate with an express server.</p>
  <p>I'm looking for a way to initialize the connection only once, and not to re-connect with every render.</p>
  <p>I first tried to wrap the connection inside a <code>useEffect</code> hook:</p>
  <pre><code>useEffect(() =&gt; {
          const socket = io(Configs.serverURL);
          ...
          socket.on('connect', () =&gt; { ... }
          socket.on('data', () =&gt; { ... }
  });
  </code></pre>
  <p>The problem with that is that I have no access to the socket object outside of this scope and that the handlers won't be updated if any of the values they depend on change.</p>
  <p>I then tried to separate the initialization from the handlers by setting some state variable</p>
  <pre><code>const [socket, setSocket] = useState(null);
  ...
  useEffect(() =&gt; {
          setSocket(io(Configs.serverURL));
  });
  
  useEffect(() =&gt; {
          socket.on('connect, () =&gt; { ... });
          ...
  }, [dependency1, dependency2])
  </code></pre>
  <p>However, I was hit by the error that says <code>Cannot read property 'on' of null</code>.</p>
  <p>To summarize: I need to initialize the socket instance outside of any local scope, I also need that to happen only once and before any other handler.</p>