typescriptadvanced
useWebSocket Hook
WebSocket hook with auto-reconnect, message queuing, and connection state tracking.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect, useRef, useCallback } from 'react';
type ReadyState = 'connecting' | 'open' | 'closing' | 'closed';
export function useWebSocket(url: string, reconnectAttempts = 5) {
const [lastMessage, setLastMessage] = useState<string | null>(null);
const [readyState, setReadyState] = useState<ReadyState>('connecting');
const wsRef = useRef<WebSocket | null>(null);
const retriesRef = useRef(0);
const connect = useCallback(() => {
const ws = new WebSocket(url);
wsRef.current = ws;
ws.onopen = () => { setReadyState('open'); retriesRef.current = 0; };
ws.onmessage = (e) => setLastMessage(e.data);
ws.onclose = () => {
setReadyState('closed');
if (retriesRef.current < reconnectAttempts) {
retriesRef.current++;
setTimeout(connect, Math.min(1000 * 2 ** retriesRef.current, 30_000));
}
};
ws.onerror = () => ws.close();
}, [url, reconnectAttempts]);
useEffect(() => {
connect();
return () => wsRef.current?.close();
}, [connect]);
const send = useCallback((data: string | object) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(typeof data === 'string' ? data : JSON.stringify(data));
}
}, []);
return { lastMessage, readyState, send };
}Use Cases
- Chat applications
- Live data feeds
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch
typescriptbeginner
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
#hooks#debounce
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage
typescriptbeginner
useClickOutside — Outside Click Detection
Detect clicks outside a referenced element to close dropdowns, modals, and popover menus.
Best for: Dropdown menus
#hooks#click-outside