DEV Community

Cover image for How to Stream LLM Responses in React Without Breaking SSE, UTF-8, or Scroll
Rishabh Srivastava
Rishabh Srivastava

Posted on

How to Stream LLM Responses in React Without Breaking SSE, UTF-8, or Scroll

Most tutorials for building an AI chat UI in React stop at calling fetch() and appending res.text() or dropping in a heavy SDK wrapper.

That works in a 5-minute demo—and immediately breaks in production or in a frontend engineering interview.

Over the last year, AI product teams have converged on four specific browser bugs that separate a toy chat box from a production-ready streaming interface:

  1. Broken JSON parsing when an SSE frame splits across two network chunks
  2. Corrupted emojis or non-ASCII text from naive TextDecoder usage
  3. "Stop generating" buttons that only flip UI state instead of closing the HTTP stream
  4. Auto-scroll fighting the user when they scroll up to read earlier tokens

Here is how to build the entire streaming pipeline cleanly in React and TypeScript using standard Web APIs (fetch, ReadableStream, TextDecoder, and AbortController).


1. Why EventSource Is Usually the Wrong Choice for LLM APIs

Browser EventSource only supports GET requests and gives you almost no control over custom headers or JSON request bodies. Because LLM endpoints take POST payloads (conversation history, model parameters, system prompts), production frontends read the stream directly from fetch().body using a ReadableStreamDefaultReader.

const res = await fetch('/api/chat', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ prompt }),
  signal: controller.signal,
});

if (!res.ok || !res.body) {
  throw new Error(`HTTP ${res.status}`);
}

const reader = res.body.getReader();
Enter fullscreen mode Exit fullscreen mode

2. Buffer Incomplete SSE Frames and Multi-Byte UTF-8 Characters

Network chunks arrive as arbitrary Uint8Array slices—they do not align with SSE event boundaries (\n\n) or even UTF-8 character boundaries.

If you do JSON.parse(chunkText) on every reader.read(), sooner or later a frame splits right in the middle of a JSON string and throws SyntaxError. And if a 4-byte emoji splits across two chunks without { stream: true }, TextDecoder replaces the split bytes with the replacement character.

The fix is a small persistent buffer paired with decoder.decode(value, { stream: true }):

const decoder = new TextDecoder();
let buffer = '';

while (true) {
  const { value, done } = await reader.read();
  if (done) break;

  buffer += decoder.decode(value, { stream: true });
  const frames = buffer.split('\n\n');
  buffer = frames.pop() ?? ''; // Save the trailing partial frame for the next chunk

  for (const frame of frames) {
    for (const line of frame.split('\n')) {
      if (!line.startsWith('data:')) continue;
      const payload = line.slice(5).trim();
      if (!payload || payload === '[DONE]') continue;

      const { delta } = JSON.parse(payload) as { delta?: string };
      if (delta) appendDelta(delta);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

3. Model Messages with Explicit States (Not isLoading: boolean)

A single isLoading boolean falls apart as soon as a user clicks Stop, retries a failed turn, or sends a second message while an old request is still winding down.

Give every assistant message a deterministic status:

export type MessageStatus = 'streaming' | 'complete' | 'stopped' | 'error';

export interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  status: MessageStatus;
  error?: string;
}
Enter fullscreen mode Exit fullscreen mode

When the user clicks Stop or navigates away (useEffect cleanup), call abortController.abort(). That cancels the underlying HTTP connection so you stop paying for server/token generation and never race stale updates into React state:

const abortRef = useRef<AbortController | null>(null);

useEffect(() => () => abortRef.current?.abort(), []);

const stop = useCallback(() => {
  abortRef.current?.abort();
  abortRef.current = null;
  setIsStreaming(false);
  setMessages((prev) =>
    prev.map((m) => (m.status === 'streaming' ? { ...m, status: 'stopped' } : m))
  );
}, []);
Enter fullscreen mode Exit fullscreen mode

4. Auto-Scroll Without Hijacking the Reader

Nothing frustrates users more than scrolling up to read an earlier code block only to get yanked back to the bottom on the next token.

Track whether the scroll container is already within ~48px of the bottom. Only pin to bottom while isPinned is true, and show a "Jump to latest" button when the user scrolls away:

export function useSmartAutoScroll<T extends HTMLElement>(dependency: unknown, thresholdPx = 48) {
  const containerRef = useRef<T | null>(null);
  const [isPinned, setIsPinned] = useState(true);

  const handleScroll = useCallback(() => {
    const el = containerRef.current;
    if (!el) return;
    const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
    setIsPinned(distance <= thresholdPx);
  }, [thresholdPx]);

  useEffect(() => {
    const el = containerRef.current;
    if (!el || !isPinned) return;
    el.scrollTop = el.scrollHeight;
  }, [dependency, isPinned]);

  return { containerRef, isPinned, handleScroll };
}
Enter fullscreen mode Exit fullscreen mode

Want to Practice This in a Live Sandbox?

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

Rishabh, the detail that separates this from the usual streaming tutorial is the 4-byte emoji one — most write-ups treat TextDecoder as a one-liner and never mention { stream: true }, so the corruption only shows up in production when someone pastes an emoji. The 48px pin threshold is the other half I would steal: a concrete number instead of "just scroll to bottom."

One thing I would add before calling this production-ready is the piece between reader.read() and setState. If the model streams fast, a setState per chunk re-renders on every token; flushing the buffer on a requestAnimationFrame cadence instead keeps the flow smooth without re-rendering dozens of times a second. Your linked guide mentions backpressure — that deserves one line in the post itself, because it is the fix that makes the other four hold up under a fast model.

And one question on the Stop button: abort() closes the client stream, but does your /api/chat handler actually cancel the upstream LLM call when the client disconnects, or does the model keep generating server-side? Your line about stopping paying for token generation only holds if the backend honors the disconnect, and that is where most "stop generating" buttons quietly leak cost. How are you handling it on the server side?