useEventSource
Server-Sent Events client.
Import
TypeScript
import { useEventSource } from '@/hooks';API
Signature
useEventSource(url, options?)
When to use
Use useEventSource instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Connect only in the browser / Client Components.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useEventSourceEditor
function SseFeed() { const { status, lastEvent } = useEventSource('/api/stream', { eventTypes: ['tick'], }); return ( <div> <p>{status}</p> <pre>{lastEvent?.data}</pre> </div> ); }
Preview
Implementation source
Full library source for useEventSource — copy into your project when you are not installing a package yet.
hooks/network/useEventSource.ts
import { useCallback, useEffect, useRef, useState } from 'react';
import type { ConnectionStatus } from '../types';
import { isBrowser } from '../utility/isBrowser';
import { useLatest } from '../utility/useLatest';
export interface UseEventSourceOptions {
autoConnect?: boolean;
withCredentials?: boolean;
reconnect?: boolean;
reconnectIntervalMs?: number;
maxRetries?: number;
eventTypes?: string[];
onMessage?: (event: MessageEvent) => void;
onOpen?: (event: Event) => void;
onError?: (event: Event) => void;
}
/**
* Server-Sent Events (EventSource) client with reconnect support.
*/
export function useEventSource(
url: string | null | undefined,
options: UseEventSourceOptions = {},
) {
const {
autoConnect = true,
withCredentials = false,
reconnect = true,
reconnectIntervalMs = 2000,
maxRetries = Infinity,
eventTypes = [],
onMessage,
onOpen,
onError,
} = options;
const [status, setStatus] = useState<ConnectionStatus>('closed');
const [lastEvent, setLastEvent] = useState<MessageEvent | null>(null);
const [retryCount, setRetryCount] = useState(0);
const sourceRef = useRef<EventSource | null>(null);
const manualClose = useRef(false);
const retryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const onMessageRef = useLatest(onMessage);
const onOpenRef = useLatest(onOpen);
const onErrorRef = useLatest(onError);
const clearRetry = () => {
if (retryTimer.current) {
clearTimeout(retryTimer.current);
retryTimer.current = null;
}
};
const disconnect = useCallback(() => {
manualClose.current = true;
clearRetry();
sourceRef.current?.close();
sourceRef.current = null;
setStatus('closed');
}, []);
const connect = useCallback(() => {
if (!isBrowser() || !url || typeof EventSource === 'undefined') return;
manualClose.current = false;
clearRetry();
sourceRef.current?.close();
setStatus('connecting');
const es = new EventSource(url, { withCredentials });
sourceRef.current = es;
es.onopen = (event) => {
setStatus('open');
setRetryCount(0);
onOpenRef.current?.(event);
};
es.onmessage = (event) => {
setLastEvent(event);
onMessageRef.current?.(event);
};
eventTypes.forEach((type) => {
es.addEventListener(type, (event) => {
const me = event as MessageEvent;
setLastEvent(me);
onMessageRef.current?.(me);
});
});
es.onerror = (event) => {
setStatus('error');
onErrorRef.current?.(event);
es.close();
sourceRef.current = null;
if (!manualClose.current && reconnect) {
setRetryCount((count) => {
if (count >= maxRetries) return count;
retryTimer.current = setTimeout(() => connect(), reconnectIntervalMs);
return count + 1;
});
}
};
}, [
url,
withCredentials,
reconnect,
reconnectIntervalMs,
maxRetries,
eventTypes,
onMessageRef,
onOpenRef,
onErrorRef,
]);
useEffect(() => {
if (autoConnect && url) connect();
return () => {
manualClose.current = true;
clearRetry();
sourceRef.current?.close();
sourceRef.current = null;
};
}, [url, autoConnect]);
return { status, lastEvent, connect, disconnect, retryCount };
}
Copy-paste example
useEventSource.example.tsx
'use client';
import { useEventSource } from '@/hooks';
export function SseFeed() {
const { status, lastEvent } = useEventSource('/api/stream', {
eventTypes: ['tick'],
});
return (
<div>
<p>{status}</p>
<pre>{lastEvent?.data}</pre>
</div>
);
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Never hardcode URLs in components shared across envs — use env vars.
- Source of truth: open
hooks/network/useEventSource.tsfor implementation details