Building a streaming LLM UI with React Server-Sent Events eliminates the multi-second dead screen that makes users think a generative app has hung. When users submit long prompts or ask for code, waiting ten to thirty seconds for a complete HTTP response drives abandonment before the answer even renders.
By streaming tokens over a persistent HTTP connection using Server-Sent Events (defined in the WHATWG Server-Sent Events specification), frontend applications can paint tokens as soon as the model emits them instead of buffering the entire completion. Shipping a production-grade streaming UI in React still requires solving three mechanical problems: buffering split SSE lines across TCP chunks, rendering incomplete markdown without layout flicker, and propagating cancellations with AbortController when a user leaves the page.

To protect frontend performance metrics, consult our Core Web Vitals SEO impact guide, review request pacing in API rate limiting and cost management, inspect typed payload parsing in structured outputs with Zod for LLM web APIs, and study escalation transitions in AI agent human handoff patterns.
How Do You Stream LLM Completions to a React Frontend with SSE?
Server-Sent Events establish a unidirectional communication channel over standard HTTP/1.1 or HTTP/2. The browser initiates a request with an Accept: text/event-stream header, and the server leaves the response body open, transmitting discrete event chunks prefixed with data: followed by double newlines (\n\n).
While the standard browser EventSource API handles SSE connections, it suffers from a major limitation: it only supports HTTP GET requests without custom body payloads or arbitrary authorization headers. Because generative language model prompts typically require large JSON payloads containing conversation histories, system prompts, and tool parameters, production web applications use the modern fetch() API paired with readable byte streams.
The client workflow consists of four operational steps:
- HTTP POST Request: The client dispatches a POST request with the user prompt payload and an
AbortSignal. - ReadableStream Reader Acquisition: The client inspects
response.body.getReader(), reading binary byte chunks asynchronously. - UTF-8 Stream Decoding: A
TextDecoderconfigured with{ stream: true }(or aTextDecoderStream) decodes UTF-8 binary buffers without corrupting multi-byte characters split across packet boundaries, then splits on newline event delimiters. - State Accumulation and Re-Rendering: React state accumulates incoming tokens, triggering lightweight incremental DOM updates.
Why Use Server-Sent Events Instead of WebSockets for Generative UI?
Many engineering teams instinctively reach for WebSockets when building real-time features. For generative text streaming, WebSockets introduce unnecessary operational complexity:
- Protocol Overhead and State Management: WebSockets require managing stateful TCP connections across load balancers, deploying specialized socket gateway clusters, and handling complex socket reconnect handshakes.
- Corporate Firewall and Proxy Traversal: Enterprise proxies and corporate firewalls frequently block or downgrade WebSocket traffic (
ws://andwss://). Conversely, SSE operates over plain HTTPS on standard port 443, effortlessly passing through edge CDNs and corporate firewalls. - Multiplexing with HTTP/2: Under HTTP/2 and HTTP/3, multiple SSE streams share a single underlying TCP connection, avoiding browser connection limits without custom socket protocols.
- Directional Simplicity: Text generation is fundamentally unidirectional (the client sends a prompt once; the server streams back dozens of tokens). WebSockets provide full-duplex communication that is redundant for conversational text generation.

| Transport Capability | fetch() + ReadableStream SSE |
Browser EventSource |
WebSockets (wss://) |
|---|---|---|---|
HTTP POST JSON payloads |
Supported | Not supported (GET only) |
Supported after handshake |
Custom Authorization headers |
Supported | Not supported | Limited in browser API |
| HTTP/2 connection multiplexing | Native | Native | Separate TCP/upgrade connection |
| Edge CDN & proxy compatibility | Standard HTTPS | Standard HTTPS | Often blocked or timed out |
| Server-side connection state | Stateless request/response | Stateless request/response | Sticky sessions / socket registry |
| Cancellation control | Native AbortController |
eventSource.close() |
socket.close() + server protocol |
How Do You Handle Stream Aborts and Network Reconnections Cleanly?
A common failure mode in generative web applications is the zombie stream. If a user clicks “Stop Generating”, closes a modal, or switches to another route while the server is mid-completion, unmanaged streams continue consuming expensive provider tokens on the backend while leaking memory on the client.
To implement clean cancellation:
- Wire AbortController to Fetch: Pass
controller.signalinto thefetch()call. When the user clicks cancel, invokecontroller.abort(), which immediately terminates the underlying HTTP stream. - Propagate Aborts to Foundation Model APIs: On your backend server, listen for the client disconnect (
request.signalin Fetch/Edge handlers orreq.on('close')in Node.js) and abort the upstream call to OpenAI, Anthropic, or local vLLM instances so you stop paying for unread tokens. - Clean Component Unmounting: Always trigger
controller.abort()inside the cleanup return function of your ReactuseEffecthooks.

{
"stream_session_telemetry": {
"session_id": "stream_sse_9918",
"transport": "HTTP/2_SSE",
"ttft_ms": 284,
"total_tokens_received": 512,
"stream_duration_seconds": 4.18,
"average_token_rate_tps": 122.4,
"abort_triggered": false,
"client_buffer_underruns": 0
}
}
Incremental Markdown Parsing and Virtual DOM Smooth Rendering
Streaming markdown presents unique UI challenges. Incomplete markdown syntax streams character by character:
- An unclosed bold tag (
**hello) - An unclosed code block fence (
```python\ndef print_value():) - A half-formed markdown link (
`[Docs](`)
If a naive React component re-parses raw string text into an AST on every single token, incomplete syntax produces visual flickering, broken layout styling, and excessive CPU consumption.

To solve this:
- Use Resilient Incremental Parsers: Libraries like
markedorreact-markdowntolerate unclosed inline tokens without throwing parser exceptions, and block-level memoization prevents already-completed paragraphs from re-rendering on every token. - Throttle Rendering Updates with
requestAnimationFrame: Instead of triggering a React state update for every single incoming token (fast models can emit 100+ tokens per second), append tokens to a mutable ref and flush them to React state once per animation frame (or every 50ms). That caps React re-renders and keeps main-thread Interaction to Next Paint (INP) responsive; see optimizing Web Vitals for generative AI widgets for layout reservation and input-yield benchmarks.
Complete React Custom Hook with AbortController Support
Here is a React custom hook that buffers partial SSE lines across TCP chunks, batches UI updates with requestAnimationFrame, flushes any trailing decoder buffer on stream end, and cleans up active connections with AbortController:
// useStreamingCompletion.ts
import { useState, useRef, useCallback, useEffect } from 'react';
interface StreamOptions {
apiEndpoint: string;
onChunk?: (chunk: string) => void;
onFinish?: (fullText: string) => void;
onError?: (err: Error) => void;
}
export function useStreamingCompletion({ apiEndpoint, onChunk, onFinish, onError }: StreamOptions) {
const [content, setContent] = useState<string>('');
const [isStreaming, setIsStreaming] = useState<boolean>(false);
const abortControllerRef = useRef<AbortController | null>(null);
const accumulatedRef = useRef<string>('');
const rafIdRef = useRef<number | null>(null);
const flushToState = useCallback(() => {
rafIdRef.current = null;
setContent(accumulatedRef.current);
}, []);
const scheduleFlush = useCallback(() => {
if (rafIdRef.current === null) {
rafIdRef.current = window.requestAnimationFrame(flushToState);
}
}, [flushToState]);
const stop = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
if (rafIdRef.current !== null) {
window.cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
}
setIsStreaming(false);
}, []);
const startStream = useCallback(async (prompt: string, contextPayload: Record<string, unknown> = {}) => {
stop();
accumulatedRef.current = '';
setContent('');
setIsStreaming(true);
const controller = new AbortController();
abortControllerRef.current = controller;
const processLine = (line: string): boolean => {
if (!line.startsWith('data:')) return false;
const dataPayload = (line.startsWith('data: ') ? line.slice(6) : line.slice(5)).trim();
if (!dataPayload) return false;
if (dataPayload === '[DONE]') return true;
try {
const parsed = JSON.parse(dataPayload) as { token?: string };
const token = parsed.token ?? '';
if (token) {
accumulatedRef.current += token;
scheduleFlush();
onChunk?.(token);
}
} catch {
// Skip malformed or heartbeat events rather than corrupting UI text
}
return false;
};
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'text/event-stream'
},
body: JSON.stringify({ prompt, ...contextPayload }),
signal: controller.signal
});
if (!response.ok || !response.body) {
throw new Error(`HTTP error ${response.status}: Failed to establish event stream.`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let lineBuffer = '';
let streamDone = false;
while (!streamDone) {
const { done, value } = await reader.read();
if (done) {
lineBuffer += decoder.decode();
if (lineBuffer) {
processLine(lineBuffer);
}
break;
}
lineBuffer += decoder.decode(value, { stream: true });
const lines = lineBuffer.split(/\r?\n/);
// Retain incomplete trailing line until the next chunk arrives
lineBuffer = lines.pop() ?? '';
for (const line of lines) {
if (processLine(line)) {
streamDone = true;
break;
}
}
}
if (rafIdRef.current !== null) {
window.cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
}
setContent(accumulatedRef.current);
setIsStreaming(false);
abortControllerRef.current = null;
onFinish?.(accumulatedRef.current);
} catch (err: unknown) {
if (err instanceof DOMException && err.name === 'AbortError') {
return;
}
setIsStreaming(false);
abortControllerRef.current = null;
onError?.(err instanceof Error ? err : new Error(String(err)));
}
}, [apiEndpoint, onChunk, onError, onFinish, scheduleFlush, stop]);
useEffect(() => stop, [stop]);
return { content, isStreaming, startStream, stop };
}
Single-line data: parsing handles OpenAI-compatible JSON chunks where each token payload sits on one line. If your backend emits multi-line data: blocks or named event: frames (such as event: tool_call or event: error), buffer lines until the blank \n\n event boundary and join consecutive data: lines with \n before parsing.
Four-Stage Streaming Generative UI Architecture SOP
Web engineering teams rolling out streaming generative interfaces should follow this four-stage implementation protocol:
Phase 1: Transport and Gateway Protocol Verification
- Configure backend responses with
Content-Type: text/event-stream; charset=utf-8andCache-Control: no-cache, no-transform, and setX-Accel-Buffering: nowhen Nginx sits in front of the app server so reverse proxies flush chunks immediately. - Configure HTTP/2 or HTTP/3 multiplexing on edge endpoints to allow multiple concurrent streams per client without hitting HTTP/1.1’s six-connection-per-origin browser limit.
- Measure Time-to-First-Token (TTFT) across desktop and mobile networks against your model provider baseline before tuning frontend rendering.
Phase 2: Frontend State Buffering and UI Virtualization
- Wrap token accumulation inside debounced state updates or animation frame batches to prevent main-thread UI locking.
- Test incomplete markdown rendering against extreme edge cases (unclosed code fences, nested blockquotes, multi-column tables).
- Implement responsive auto-scrolling that tracks incoming tokens but smoothly disengages when the user manually scrolls up.
Phase 3: Abort Propagation and Backend Token Protection
- Wire client-side
AbortControllertriggers to visible cancel buttons, modal dismiss events, and route change hooks. - Configure backend gateway listeners that intercept socket termination and immediately signal cancellation to foundation model APIs.
- Monitor wasted token ratios (tokens billed by providers after client disconnects) to ensure zero token leakage.
Phase 4: Telemetry and Error Recovery Automation
- Track connection drop rates, average streaming duration, and parsing exceptions in client error logging tools.
- Implement automatic exponential backoff retry for transient network disconnects without resetting already-streamed conversational state.
- Measure Core Web Vitals to confirm that streaming rendering does not degrade Interaction to Next Paint (INP) scores.
Conclusion
Server-Sent Events give React applications token-by-token streaming over standard HTTPS without WebSocket gateway state. Pairing a line-buffered fetch() reader with requestAnimationFrame state batching, resilient incremental markdown rendering, and end-to-end AbortController propagation keeps the browser responsive and stops backend token spend the moment a user cancels or navigates away.



