useEventSource
useEventSource is a hook that allows you to subscribe to an EventSource and receive updates in real-time.
useEventSource wraps the EventSource API (Server-Sent Events) to establish a one-way connection from a server to the browser. It returns an object with status (connection state), data (the latest message), error, close (to disconnect), and open (to reconnect). You can listen to named events and control whether the connection opens immediately or is deferred.
When to Use
- Receiving real-time server updates such as live feeds, notifications, or progress events
- Building dashboards that display streaming data from a server endpoint
- Implementing server-push features where the client only needs to receive (not send) data
Notes
- SSR-safe: Returns a default state with no active connection during server-side rendering. No
EventSourceconstructor is called on the server. - Reconnection: The browser’s native
EventSourceautomatically reconnects on connection loss. Use thestatusfield to track the current connection state. - Related hooks: See also
useFetchEventSourcefor SSE connections that need custom HTTP methods (e.g., POST) or headers.
Usage
Live Editor
function Demo() { const { status, data, error, close, open } = useEventSource( "https://sse.dev/test", [], { immediate: false, } ); return ( <div> <div>Status: {status}</div> <div>Data: {JSON.stringify(data)}</div> <div>Error: {error}</div> <button onClick={open}>open</button> <button onClick={close}>Close</button> </div> ); };
Result
API
UseEventSourceOptions
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| immediate | immediately open the connection, enabled by default | boolean | - |
| autoReconnect | Automatically reconnect when the connection is disconnected | UseEventSourceAutoReconnectOptions | - |
UseEventSourceAutoReconnectOptions
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| retries | The number of retries, if it is a function, it will be called to determine whether to retry | number | (() => boolean) | - |
| delay | The delay time before reconnecting | number | - |
| onFailed | Callback when reconnection fails | () => void | - |
UseEventSourceReturn
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| eventSourceRef | EventSource instance | React.MutableRefObject<EventSource | null> (Required) | - |
| data | The data received | string | null (Required) | - |
| error | The error occurred | Event | null (Required) | - |
| status | The status of the connection | EventSourceStatus (Required) | - |
| lastEventId | The last event ID | string | null (Required) | - |
| event | The event name | string | null (Required) | - |
| close | Close the connection | () => void (Required) | - |
| open | Open the connection | () => void (Required) | - |
EventSourceStatus
export type EventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';