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

NameTypeDescriptionDefault ValueOptional
urlstringThe URL of the Socket server.-No
optionsobjectSocket.IO connection options.-Yes
options.reconnectionDelaynumberDelay before attempting to reconnect.5000msYes
options.reconnectionbooleanWhether to attempt reconnections.trueYes
options.withCredentialsbooleanWhether to send credentials with requests.falseYes
options.transportsstring[]Transport methods to use.["websocket"]Yes
options.autoConnectbooleanWhether to automatically connect.trueYes
options.timeoutnumberConnection timeout in milliseconds.20000msYes

Return Values

NameTypeDescription
socketSocketThe Socket.IO client instance.
isConnectedbooleanIndicates if the socket is connected.
connect() => voidFunction to manually connect to the socket.
disconnect() => voidFunction to manually disconnect from the socket.