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 EventSource constructor is called on the server.
  • Reconnection: The browser’s native EventSource automatically reconnects on connection loss. Use the status field to track the current connection state.
  • Related hooks: See also useFetchEventSource for 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

PropertyDescriptionTypeDefaultValue
immediateimmediately open the connection, enabled by defaultboolean-
autoReconnectAutomatically reconnect when the connection is disconnectedUseEventSourceAutoReconnectOptions-

UseEventSourceAutoReconnectOptions

PropertyDescriptionTypeDefaultValue
retriesThe number of retries, if it is a function, it will be called to determine whether to retrynumber | (() => boolean)-
delayThe delay time before reconnectingnumber-
onFailedCallback when reconnection fails() => void-

UseEventSourceReturn

PropertyDescriptionTypeDefaultValue
eventSourceRefEventSource instanceReact.MutableRefObject<EventSource | null> (Required)-
dataThe data receivedstring | null (Required)-
errorThe error occurredEvent | null (Required)-
statusThe status of the connectionEventSourceStatus (Required)-
lastEventIdThe last event IDstring | null (Required)-
eventThe event namestring | null (Required)-
closeClose the connection() => void (Required)-
openOpen the connection() => void (Required)-

EventSourceStatus

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