Lesson 4 of 8
WebSockets & Real-Time Data
WebSockets provide bidirectional real-time communication. In React, the pattern is: establish the WebSocket in a custom hook with proper cleanup, handle reconnection, and use startTransition for incoming messages to keep the UI responsive.
useWebSocket - Production Hook
import { useState, useEffect, useRef, useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
interface WebSocketOptions {
reconnectInterval?: number;
maxReconnects?: number;
}
function useWebSocket<T>(url: string, options: WebSocketOptions = {}) {
const { reconnectInterval = 3000, maxReconnects = 5 } = options;
const [lastMessage, setLastMessage] = useState<T | null>(null);
const [status, setStatus] = useState<'connecting' | 'open' | 'closed' | 'error'>('connecting');
const wsRef = useRef<WebSocket | null>(null);
const reconnectCount = useRef(0);
const reconnectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const connect = useCallback(() => {
wsRef.current = new WebSocket(url);
wsRef.current.onopen = () => {
setStatus('open');
reconnectCount.current = 0; // reset on successful connection
};
wsRef.current.onmessage = (event) => {
try {
const data = JSON.parse(event.data) as T;
setLastMessage(data);
} catch { /* ignore malformed messages */ }
};
wsRef.current.onerror = () => setStatus('error');
wsRef.current.onclose = () => {
setStatus('closed');
if (reconnectCount.current < maxReconnects) {
reconnectCount.current++;
reconnectTimer.current = setTimeout(connect, reconnectInterval);
}
};
}, [url, reconnectInterval, maxReconnects]);
useEffect(() => {
connect();
return () => {
if (reconnectTimer.current) clearTimeout(reconnectTimer.current);
wsRef.current?.close();
};
}, [connect]);
const send = useCallback((data: unknown) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(data));
}
}, []);
return { lastMessage, status, send };
}
// Usage: Live notifications
interface Notification { id: string; type: 'info' | 'success' | 'error'; message: string; }
function NotificationCenter() {
const queryClient = useQueryClient();
const [notifications, setNotifications] = useState<Notification[]>([]);
const { lastMessage, status } = useWebSocket<Notification>(
'wss://api.example.com/notifications'
);
// React 18: mark incoming WS messages as non-urgent
import { startTransition } from 'react';
useEffect(() => {
if (!lastMessage) return;
startTransition(() => {
setNotifications(prev => [lastMessage, ...prev.slice(0, 49)]);
// Invalidate relevant queries on data change events
if (lastMessage.type === 'success') {
queryClient.invalidateQueries({ queryKey: ['users'] });
}
});
}, [lastMessage, queryClient]);
return (
<div>
<span style={{ color: status === 'open' ? 'green' : 'red' }}>โ {status}</span>
{notifications.map(n => <NotificationItem key={n.id} notification={n} />)}
</div>
);
}Tip
Tip
Practice WebSockets RealTime Data in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for WebSockets & Real-Time Data
Practice Task
Note
Practice Task - (1) Write a working example of WebSockets RealTime Data from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with WebSockets RealTime Data is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?