realtime-react-hooksReact hooks for real-time data with SSE, WebSocket, and SWR integration. Covers connection management, reconnection logic, and optimistic updates. Use when building React apps with real-time features. Triggers on SSE hook, WebSocket hook, real-time React, useEventSource, live updates.
Install via ClawdBot CLI:
clawdbot install wpank/realtime-react-hooksProduction patterns for real-time data in React applications using SSE, WebSocket, and SWR.
npx clawhub@latest install realtime-react-hooks
import { useEffect, useRef, useState, useCallback } from 'react';
interface UseSSEOptions<T> {
url: string;
onMessage?: (data: T) => void;
onError?: (error: Event) => void;
enabled?: boolean;
}
export function useSSE<T>({
url,
onMessage,
onError,
enabled = true,
}: UseSSEOptions<T>) {
const [data, setData] = useState<T | null>(null);
const [isConnected, setIsConnected] = useState(false);
const eventSourceRef = useRef<EventSource | null>(null);
useEffect(() => {
if (!enabled) return;
const eventSource = new EventSource(url);
eventSourceRef.current = eventSource;
eventSource.onopen = () => {
setIsConnected(true);
};
eventSource.onmessage = (event) => {
try {
const parsed = JSON.parse(event.data) as T;
setData(parsed);
onMessage?.(parsed);
} catch (e) {
console.error('SSE parse error:', e);
}
};
eventSource.onerror = (error) => {
setIsConnected(false);
onError?.(error);
};
return () => {
eventSource.close();
eventSourceRef.current = null;
};
}, [url, enabled]);
const close = useCallback(() => {
eventSourceRef.current?.close();
setIsConnected(false);
}, []);
return { data, isConnected, close };
}
interface UseWebSocketOptions {
url: string;
onMessage?: (data: unknown) => void;
reconnect?: boolean;
maxRetries?: number;
}
export function useWebSocket({
url,
onMessage,
reconnect = true,
maxRetries = 5,
}: UseWebSocketOptions) {
const [isConnected, setIsConnected] = useState(false);
const wsRef = useRef<WebSocket | null>(null);
const retriesRef = useRef(0);
const connect = useCallback(() => {
const ws = new WebSocket(url);
wsRef.current = ws;
ws.onopen = () => {
setIsConnected(true);
retriesRef.current = 0;
};
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
onMessage?.(data);
} catch {
onMessage?.(event.data);
}
};
ws.onclose = () => {
setIsConnected(false);
if (reconnect && retriesRef.current < maxRetries) {
retriesRef.current++;
const delay = Math.min(1000 * 2 ** retriesRef.current, 30000);
setTimeout(connect, delay);
}
};
ws.onerror = () => {
ws.close();
};
}, [url, onMessage, reconnect, maxRetries]);
useEffect(() => {
connect();
return () => wsRef.current?.close();
}, [connect]);
const send = useCallback((data: unknown) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(data));
}
}, []);
return { isConnected, send };
}
import useSWR from 'swr';
import { useEffect } from 'react';
export function useRealtimeData<T>(
key: string,
fetcher: () => Promise<T>
) {
const { data, mutate, ...rest } = useSWR(key, fetcher);
// Subscribe to real-time updates
useEffect(() => {
const eventSource = new EventSource(`/api/events/${key}`);
eventSource.onmessage = (event) => {
const update = JSON.parse(event.data);
// Optimistically update cache
mutate((current) => {
if (!current) return update;
return { ...current, ...update };
}, false); // false = don't revalidate
};
return () => eventSource.close();
}, [key, mutate]);
return { data, mutate, ...rest };
}
interface UseSubscriptionOptions {
channels: string[];
onEvent: (channel: string, data: unknown) => void;
}
export function useSubscription({ channels, onEvent }: UseSubscriptionOptions) {
const { send, isConnected } = useWebSocket({
url: '/api/ws',
onMessage: (msg: any) => {
if (msg.type === 'event') {
onEvent(msg.channel, msg.data);
}
},
});
useEffect(() => {
if (!isConnected) return;
// Subscribe to channels
channels.forEach((channel) => {
send({ type: 'subscribe', channel });
});
return () => {
channels.forEach((channel) => {
send({ type: 'unsubscribe', channel });
});
};
}, [channels, isConnected, send]);
return { isConnected };
}
export function ConnectionStatus({ isConnected }: { isConnected: boolean }) {
return (
<div className="flex items-center gap-2">
<span
className={cn(
'size-2 rounded-full',
isConnected ? 'bg-success animate-pulse' : 'bg-destructive'
)}
/>
<span className="text-xs text-muted-foreground">
{isConnected ? 'Live' : 'Disconnected'}
</span>
</div>
);
}
mutate(data, false) for optimistic updates// SSE
const { data, isConnected } = useSSE({ url: '/api/events' });
// WebSocket
const { isConnected, send } = useWebSocket({
url: 'wss://api.example.com/ws',
onMessage: (data) => console.log(data),
});
// SWR + Real-time
const { data } = useRealtimeData('metrics', fetchMetrics);
// Subscriptions
useSubscription({
channels: ['user:123', 'global'],
onEvent: (channel, data) => updateState(channel, data),
});
Generated Mar 1, 2026
A dashboard for trading platforms or fintech apps that displays real-time stock prices, market trends, and portfolio updates. Uses SSE hooks for streaming price data and WebSocket hooks for instant trade execution notifications, ensuring users see up-to-the-second changes without manual refreshes.
An application like Google Docs where multiple users edit a document simultaneously. Implements WebSocket hooks for live cursor positions and text updates, along with SWR integration for optimistic UI updates to reduce latency and enhance user collaboration in real-time.
A system for tracking IoT devices such as sensors in manufacturing or smart home environments. Uses SSE hooks to stream sensor data (e.g., temperature, humidity) to a React dashboard, with subscription hooks to manage alerts and updates across multiple device channels efficiently.
A web app for sports leagues or betting platforms that shows live scores, player stats, and game events. Leverages SSE hooks for score updates and WebSocket hooks for push notifications on key plays, providing fans with instant access to game developments as they happen.
A chat system for customer service where agents and customers communicate in real-time. Integrates WebSocket hooks for message sending and receiving, with connection status indicators to show online/offline states, ensuring reliable and responsive support interactions.
Offer this skill as part of a SaaS platform for building real-time React applications, charging monthly or annual fees based on usage tiers (e.g., number of connections or data volume). Targets startups and enterprises needing scalable live data solutions, with revenue from recurring subscriptions.
Provide consulting services to integrate these hooks into client projects, such as custom dashboards or chat apps, with fees based on project scope or hourly rates. Focuses on industries like finance or IoT where real-time capabilities are critical, generating revenue from one-time or ongoing contracts.
Release the hooks as open-source on platforms like GitHub to build community adoption, then monetize through premium features like advanced analytics, enterprise support, or hosted solutions. Attracts developers and small teams, with revenue from upsells and support packages.
💬 Integration Tip
Start by integrating the SSE hook for simple data streams before adding WebSocket hooks for bidirectional communication, and use SWR to cache and optimize updates for better performance in production apps.
Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
Expert frontend design guidelines for creating beautiful, modern UIs. Use when building landing pages, dashboards, or any user interface.
Use when building UI with shadcn/ui components, Tailwind CSS layouts, form patterns with react-hook-form and zod, theming, dark mode, sidebar layouts, mobile navigation, or any shadcn component question.
Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when building web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
Create distinctive, production-grade static sites with React, Tailwind CSS, and shadcn/ui — no mockups needed. Generates bold, memorable designs from plain text requirements with anti-AI-slop aesthetics, mobile-first responsive patterns, and single-file bundling. Use when building landing pages, marketing sites, portfolios, dashboards, or any static web UI. Supports both Vite (pure static) and Next.js (Vercel deploy) workflows.
AI skill for automated UI audits. Evaluate interfaces against proven UX principles for visual hierarchy, accessibility, cognitive load, navigation, and more. Based on Making UX Decisions by Tommy Geoco.