Overview
TheuseSocket hook provides access to the Socket.IO client instance and connection state. This is a foundational hook that other hooks use to communicate with the server.
Usage
Return Value
The hook returns an object with the following properties:The Socket.IO client instance. Will be
null until initialized. Once connected, you can use this to emit events and listen for server responses.Whether the socket is currently connected to the server. Use this to show connection status or disable features when disconnected.
Whether the socket has been initialized. This becomes
true once the SocketProvider mounts on the client side.Implementation Details
TheuseSocket hook is a simple wrapper around React Context:
src/hooks/use-socket.ts
SocketProvider context provider, which:
- Creates a Socket.IO client connection to
/api/socket/io - Manages connection state (connected/disconnected)
- Handles automatic reconnection
- Provides the socket instance to all child components
Socket Configuration
The socket is configured with these settings:src/contexts/socket-provider.tsx:46-50
- path: Custom Socket.IO server path
- transports: Prefer WebSocket, fall back to polling
- autoConnect: Automatically connect when created
Socket Provider Setup
TheuseSocket hook must be used within a SocketProvider. Watch N Chill sets this up in the root layout:
src/app/layout.tsx
Connection Lifecycle
The socket goes through these states:- Not initialized (
isInitialized: false,socket: null) - Before SocketProvider mounts - Initialized, connecting (
isInitialized: true,isConnected: false,socket: Socket) - Socket created, attempting connection - Connected (
isInitialized: true,isConnected: true,socket: Socket) - Successfully connected to server - Disconnected (
isInitialized: true,isConnected: false,socket: Socket) - Connection lost, will auto-reconnect
Example: Custom Event Listener
Related Hooks
- useRoom - Built on useSocket, manages room state and membership
- useVideoSync - Built on useSocket, handles video synchronization
- useCreateRoom - Uses useSocket to create rooms
- useJoinRoom - Uses useSocket to join rooms
Socket.IO Events
See the Socket.IO Events documentation for all available events:Room Events
Create, join, and manage rooms
Video Events
Control synchronized video playback
Chat Events
Send messages and typing indicators