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';