# useServerSentEvent [Русский](./README.md) React hook for working with Server-Sent Events (SSE). ## Requirements - React 18 or newer; - a browser with `EventSource` support; - Bun is only required to run the local demo. ## Installation ```bash npm install use-server-sent-event ``` ## Usage ```tsx import { useServerSentEvent } from 'use-server-sent-event'; type ServerMessage = { id: string; value: number; }; function Messages() { const { data, error, isConnected } = useServerSentEvent( '/api/events', undefined, ); if (error) { return

SSE error: {error.message}

; } return (

Status: {isConnected ? 'Connected' : 'Disconnected'}

{JSON.stringify(data, null, 2)}
); } ``` By default, each event payload is parsed with `JSON.parse`. Numbers are valid JSON values; provide a custom parser for plain text payloads. ## API ### `useServerSentEvent(url, initialState?, options?)` The existing two-argument signature remains supported. The third argument is optional. Options: - `parse` — converts the raw payload into `T`; defaults to `JSON.parse`; - `eventName` — SSE event name, defaulting to `message`; - `withCredentials` — include cookies for cross-origin connections; - `reconnect` — keep native `EventSource` reconnect behavior enabled, default `true`; - `resetOnUrlChange` — reset `data` and `error` when the URL changes, default `true`; - `enabled` — create a connection only when `true`, default `true`. Return values: - `data` — the latest data or `undefined`; - `error` — the latest connection or parsing error; - `isConnected` — `true` after the `open` event. Native `EventSource` does not support arbitrary HTTP headers. Use cookies, query parameters, or another transport for authentication headers. ## SSR The connection is not created on the server. During SSR, the hook returns `initialState`, `error: null`, and `isConnected: false`. Use the same `initialState` on the server and client to avoid hydration mismatches. ## Demo and checks Run the complete demo from the repository root: ```bash npm run demo ``` Open for the vanilla interface or for the React interface using the built `dist/index.js` artifact. Run the release checks with: ```bash npm run verify ``` See [examples/README.md](./examples/README.md) for details. ## License MIT. See [LICENSE](./LICENSE).