Docs
useSocket
Manage Socket connections, handling messages, errors, and connection states.
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-socket
Usage
"use client"
import * as React from "react"
import { url } from "@/config"
import { useSocket } from "@/hooks/use-socket"
export function Component() {
const { socket, isConnected, connect, disconnect } = useSocket(url, {
reconnectionDelay: 5000,
reconnection: true,
})
React.useEffect(() => {
if (socket) {
socket.on("message", (data) => {
console.log("Received message:", data)
})
}
return () => {
if (socket) {
socket.off("message")
}
}
}, [socket])
return (
<div>
<div>Status: {isConnected ? "🟢 Connected" : "🔴 Disconnected"}</div>
{isConnected ? (
<button variant="destructive" onClick={disconnect}>
Disconnect
</button>
) : (
<button onClick={connect}>Connect</button>
)}
<button
onClick={() => {
if (socket) {
socket.emit("message", { message: "Hello from useKit!" })
}
}}
>
Send Message
</button>
<p>Open the console to see the logs</p>
</div>
)
}
API Reference
Parameters
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
url | string | The URL of the Socket server. | - | No |
options | object | Socket.IO connection options. | - | Yes |
options.reconnectionDelay | number | Delay before attempting to reconnect. | 5000ms | Yes |
options.reconnection | boolean | Whether to attempt reconnections. | true | Yes |
options.withCredentials | boolean | Whether to send credentials with requests. | false | Yes |
options.transports | string[] | Transport methods to use. | ["websocket"] | Yes |
options.autoConnect | boolean | Whether to automatically connect. | true | Yes |
options.timeout | number | Connection timeout in milliseconds. | 20000ms | Yes |
Return Values
Name | Type | Description |
---|---|---|
socket | Socket | The Socket.IO client instance. |
isConnected | boolean | Indicates if the socket is connected. |
connect | () => void | Function to manually connect to the socket. |
disconnect | () => void | Function to manually disconnect from the socket. |