useEventSource

useEventSource 是一个 hook,允许您订阅 EventSource 并实时接收更新。

useEventSource 封装了 EventSource API(Server-Sent Events),用于建立从服务器到浏览器的单向连接。它返回一个包含 status(连接状态)、data(最新消息)、errorclose(断开连接)和 open(重新连接)的对象。你可以监听命名事件,并控制连接是否立即打开或延迟。

使用场景

  • 接收实时服务器更新,如实时推送、通知或进度事件
  • 构建显示来自服务器端点的流数据的仪表板
  • 实现客户端只需要接收(不发送)数据的服务器推送功能

注意事项

  • SSR 安全:在服务端渲染期间返回无活动连接的默认状态。服务端不会调用 EventSource 构造函数。
  • 重新连接:浏览器原生的 EventSource 在连接丢失时会自动重新连接。使用 status 字段跟踪当前连接状态。
  • 相关 hooks:参见 useFetchEventSource,用于需要自定义 HTTP 方法(例如 POST)或请求头的 SSE 连接。
Live Editor
function Demo() {
  const { status, data, error, close, open } = useEventSource(
    "https://sse.dev/test",
    [],
    {
      immediate: false,
    }
  );

  return (
    <div>
      <div>状态: {status}</div>
      <div>数据: {JSON.stringify(data)}</div>
      <div>错误: {error}</div>
      <button onClick={open}>打开</button>
      <button onClick={close}>关闭</button>
    </div>
  );
}
Result

API

UseEventSourceOptions

参数名描述类型默认值
immediate立即打开连接, 默认打开boolean-
autoReconnect连接断开时自动重连UseEventSourceAutoReconnectOptions-

UseEventSourceAutoReconnectOptions

参数名描述类型默认值
retries重试次数,如果是函数,会调用来判断是否重试number | (() => boolean)-
delay重连前的延迟时间number-
onFailed重连失败时的回调() => void-

UseEventSourceReturn

参数名描述类型默认值
eventSourceRefEventSource 实例React.MutableRefObject<EventSource | null> (必填)-
data接收到的数据string | null (必填)-
error发生的错误Event | null (必填)-
status连接的状态EventSourceStatus (必填)-
lastEventId最后的事件 IDstring | null (必填)-
event事件名string | null (必填)-
close关闭连接() => void (必填)-
open打开连接() => void (必填)-

EventSourceStatus

export type EventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';