生产级 React 实时数据 Hooks
简介
OpenClaw 社区出品的 React 实时数据 Hooks,提供 SSE/WebSocket 连接管理与乐观更新能力,助力构建高性能实时交互应用。
原始描述
React 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.
通过你的 Agent 添加
安装目录:realtime-react-hooks/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。
点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。
或者手动安装
包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可;
目录名不用换,也不要把包直接解压到 skills 根目录。
技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。
中文使用说明 来自收录源
核心用法
本 Skill 提供 5 种生产级 React Hooks 模式,覆盖实时数据场景的核心需求:
- useSSE — Server-Sent Events 基础 Hook,自动解析 JSON、管理连接状态、提供手动关闭方法
- useWebSocket — 带指数退避重连的 WebSocket Hook,支持自定义重试次数、发送消息、连接状态追踪
- useRealtimeData — SWR + SSE 组合模式,实现缓存优先 + 实时更新的乐观更新策略
- useSubscription — 频道订阅模式,自动处理订阅/取消订阅生命周期,适合多房间场景
- ConnectionStatus — 连接状态可视化组件,提供 Live/Disconnected 状态指示
显著优点
- 类型安全:完整 TypeScript 泛型支持,
UseSSEOptions<T> 确保消息类型推断
- 生产就绪:内置错误边界(try/catch JSON 解析)、指数退避重连、内存泄漏防护(useRef + cleanup)
- 架构灵活:三种技术栈(SSE/WebSocket/SWR)独立可选,可按场景组合
- 乐观更新:SWR 集成模式展示
mutate(data, false) 最佳实践,避免冗余请求
- 零依赖侵入:纯 React 实现,不绑定特定状态管理库
潜在缺点与局限性
- T3 来源风险:个人开发者维护,无组织级 SLA 保障,长期维护存在不确定性
- 示例占位符:所有 URL(
/api/events、wss://api.example.com)需手动替换,新手可能直接复制导致 404
- 无测试覆盖:纯文档型 Skill 未提供单元测试或 Storybook 示例
- 浏览器兼容性:EventSource 在 IE11 需 polyfill,部分企业环境受限
- 重连策略固定:指数退避公式
1000 * 2^retries 硬编码,无法自定义为线性退避或抖动策略
适合人群
- 需快速搭建实时功能的 React 中级开发者
- 技术选型阶段对比 SSE vs WebSocket 的团队
- 已有 SWR 项目,希望增量添加实时更新的工程
- 学习 React 副作用清理、useRef 持久化等进阶模式的开发者
常规风险
风险项
等级
说明
代码执行
无
T-MD 纯文档,无可执行代码
网络请求
无
仅示例 URL,无实际请求发起
数据隐私
无
不收集、不传输用户数据
依赖注入
无
无 npm 依赖声明
来源可信度
低
T3 个人开发者,建议人工审查后使用
UseSSEOptions<T> 确保消息类型推断mutate(data, false) 最佳实践,避免冗余请求- T3 来源风险:个人开发者维护,无组织级 SLA 保障,长期维护存在不确定性
- 示例占位符:所有 URL(
/api/events、wss://api.example.com)需手动替换,新手可能直接复制导致 404 - 无测试覆盖:纯文档型 Skill 未提供单元测试或 Storybook 示例
- 浏览器兼容性:EventSource 在 IE11 需 polyfill,部分企业环境受限
- 重连策略固定:指数退避公式
1000 * 2^retries硬编码,无法自定义为线性退避或抖动策略
适合人群
- 需快速搭建实时功能的 React 中级开发者
- 技术选型阶段对比 SSE vs WebSocket 的团队
- 已有 SWR 项目,希望增量添加实时更新的工程
- 学习 React 副作用清理、useRef 持久化等进阶模式的开发者
常规风险
风险项
等级
说明
代码执行
无
T-MD 纯文档,无可执行代码
网络请求
无
仅示例 URL,无实际请求发起
数据隐私
无
不收集、不传输用户数据
依赖注入
无
无 npm 依赖声明
来源可信度
低
T3 个人开发者,建议人工审查后使用
| 风险项 | 等级 | 说明 |
|---|---|---|
| 代码执行 | 无 | T-MD 纯文档,无可执行代码 |
| 网络请求 | 无 | 仅示例 URL,无实际请求发起 |
| 数据隐私 | 无 | 不收集、不传输用户数据 |
| 依赖注入 | 无 | 无 npm 依赖声明 |
| 来源可信度 | 低 | T3 个人开发者,建议人工审查后使用 |
使用建议:作为代码参考库而非 npm 包直接安装,建议逐文件复制到项目并按需调整 URL、重连策略、错误上报逻辑。
技能正文
name: realtime-react-hooks
model: standard
description: React 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.
Real-Time React Hooks
Production patterns for real-time data in React applications using SSE, WebSocket, and SWR.
Installation
OpenClaw / Moltbot / Clawbot
npx clawhub@latest install realtime-react-hooks
When to Use
- React apps needing live data updates
- Dashboards with real-time metrics
- Chat interfaces, notifications
- Any UI that should update without refresh
Pattern 1: SSE Hook
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 };
}
Pattern 2: WebSocket Hook with Reconnection
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 };
}
Pattern 3: SWR with Real-Time Updates
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 };
}
Pattern 4: Subscription Hook
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 };
}
Pattern 5: Connection Status Indicator
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>
);
}
Related Skills
- Meta-skill: ai/skills/meta/realtime-dashboard/ — Complete realtime dashboard guide
- resilient-connections — Retry logic
- design-systems/animated-financial-display — Number animations
NEVER Do
- NEVER forget cleanup — Always close connections on unmount
- NEVER reconnect infinitely — Use max retries with exponential backoff
- NEVER parse without try/catch — Server might send malformed data
- NEVER mutate and revalidate — Use
mutate(data, false) for optimistic updates
- NEVER ignore connection state — Show users when they're disconnected
Quick Reference
// 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),
});
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 };
}
Pattern 2: WebSocket Hook with Reconnection
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 };
}
Pattern 3: SWR with Real-Time Updates
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 };
}
Pattern 4: Subscription Hook
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 };
}
Pattern 5: Connection Status Indicator
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>
);
}
Related Skills
- Meta-skill: ai/skills/meta/realtime-dashboard/ — Complete realtime dashboard guide
- resilient-connections — Retry logic
- design-systems/animated-financial-display — Number animations
NEVER Do
- NEVER forget cleanup — Always close connections on unmount
- NEVER reconnect infinitely — Use max retries with exponential backoff
- NEVER parse without try/catch — Server might send malformed data
- NEVER mutate and revalidate — Use
mutate(data, false) for optimistic updates
- NEVER ignore connection state — Show users when they're disconnected
Quick Reference
// 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),
});
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 };
}
Pattern 4: Subscription Hook
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 };
}
Pattern 5: Connection Status Indicator
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>
);
}
Related Skills
- Meta-skill: ai/skills/meta/realtime-dashboard/ — Complete realtime dashboard guide
- resilient-connections — Retry logic
- design-systems/animated-financial-display — Number animations
NEVER Do
- NEVER forget cleanup — Always close connections on unmount
- NEVER reconnect infinitely — Use max retries with exponential backoff
- NEVER parse without try/catch — Server might send malformed data
- NEVER mutate and revalidate — Use
mutate(data, false) for optimistic updates
- NEVER ignore connection state — Show users when they're disconnected
Quick Reference
// 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),
});
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>
);
}
Related Skills
- Meta-skill: ai/skills/meta/realtime-dashboard/ — Complete realtime dashboard guide
- resilient-connections — Retry logic
- design-systems/animated-financial-display — Number animations
NEVER Do
- NEVER forget cleanup — Always close connections on unmount
- NEVER reconnect infinitely — Use max retries with exponential backoff
- NEVER parse without try/catch — Server might send malformed data
- NEVER mutate and revalidate — Use
mutate(data, false) for optimistic updates
- NEVER ignore connection state — Show users when they're disconnected
Quick Reference
// 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),
});
- NEVER forget cleanup — Always close connections on unmount
- NEVER reconnect infinitely — Use max retries with exponential backoff
- NEVER parse without try/catch — Server might send malformed data
- NEVER mutate and revalidate — Use
mutate(data, false)for optimistic updates - NEVER ignore connection state — Show users when they're disconnected
Quick Reference
// 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),
});
// 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),
});
正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。