@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
| Field | Type | Description |
|---|---|---|
isConnected | boolean | true when the socket has an active confirmed connection. |
isConnecting | boolean | true during the initial connection or reconnection attempts. |
socketId | string | undefined | The server-assigned ID. undefined when disconnected. |
error | Error | null | The most recent connection error. |
connect() | () => void | Start connecting. No-op if already connected. |
disconnect() | () => void | Close 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 />
</>
);
}