Skip to main content

useEventSource

useEventSource is a hook that allows you to subscribe to an EventSource and receive updates in real-time.

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
Loading...

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