useEventSource
useEventSource 是一個 hook,允許您訂閱 EventSource 並實時接收更新。
useEventSource 封裝了 EventSource API(Server-Sent Events),用於建立從伺服器到瀏覽器的單向連線。它回傳一個物件,包含 status(連線狀態)、data(最新訊息)、error、close(斷開連線)和 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
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| eventSourceRef | EventSource 实例 | React.MutableRefObject<EventSource | null> (必填) | - |
| data | 接收到的数据 | string | null (必填) | - |
| error | 发生的错误 | Event | null (必填) | - |
| status | 连接的状态 | EventSourceStatus (必填) | - |
| lastEventId | 最后的事件 ID | string | null (必填) | - |
| event | 事件名 | string | null (必填) | - |
| close | 关闭连接 | () => void (必填) | - |
| open | 打开连接 | () => void (必填) | - |
EventSourceStatus
export type EventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';