@void-snippets/react

useSocketConnection

Connection state, socketId, error, connect(), and disconnect().

#What it does

Tracks the socket's connection state reactively and exposes connect and disconnect controls. Safe to call from multiple components at once.

#Return values

FieldTypeDescription
isConnectedbooleantrue when the socket has an active confirmed connection.
isConnectingbooleantrue during the initial connection or reconnection attempts.
socketIdstring | undefinedThe server-assigned ID. undefined when disconnected.
errorError | nullThe most recent connection error.
connect()() => voidStart connecting. No-op if already connected.
disconnect()() => voidClose gracefully and stop reconnection.

#Example

tsx
function AppShell() {
  const { connect, disconnect, isConnected, isConnecting, error } = useSocketConnection();

  useEffect(() => {
    connect();
    return () => disconnect();
  }, []);

  return (
    <>
      {isConnecting && <Banner color="blue">Connecting…</Banner>}
      {error && !isConnecting && (
        <Banner color="red">
          Connection failed: {error.message}
          <Button size="sm" onClick={connect}>Retry</Button>
        </Banner>
      )}
      <App />
    </>
  );
}