← Blog

Claude API Streaming UI: Building a React Component

2026-11-21 · 5 min read · SubToAPI Team

Building a streaming UI for Claude in React

If you're searching for how to build a Claude API streaming UI React component, you're probably past the "basic chatbot" stage and need text to appear token-by-token instead of waiting for a full response. This is what makes an AI product feel responsive — users see words appear in real time instead of staring at a spinner for 5–15 seconds.

The short answer: Claude's API (and any API built on top of it, like SubToAPI) streams responses as Server-Sent Events (SSE). Your React component needs to open a streaming connection, read incoming chunks, append them to local state as they arrive, and handle cleanup when the component unmounts or the user cancels. Below is a complete, production-usable pattern.

How streaming actually works

When you make a streaming request, the server doesn't send one big JSON blob. It sends a sequence of events, each containing a small delta of text. The client reads these events one at a time and updates the UI incrementally.

A typical streaming request looks like this with curl:

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4",
    "max_tokens": 1024,
    "stream": true,
    "messages": [{"role": "user", "content": "Explain event loops in Node.js"}]
  }'

Instead of one response, you get a stream of event: and data: lines, each carrying a content delta. Your job on the frontend is to parse these and update a text buffer.

The React component

Here's a self-contained component that handles the full lifecycle: sending the request, reading the stream, updating state token by token, and cleaning up on unmount or cancellation.

import { useState, useRef, useCallback } from "react";

function useClaudeStream() {
  const [text, setText] = useState("");
  const [isStreaming, setIsStreaming] = useState(false);
  const controllerRef = useRef(null);

  const send = useCallback(async (prompt) => {
    setText("");
    setIsStreaming(true);
    const controller = new AbortController();
    controllerRef.current = controller;

    try {
      const res = await fetch("https://api.subtoapi.app/v1/messages", {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${process.env.REACT_APP_SUBTOAPI_KEY}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          model: "claude-sonnet-4",
          max_tokens: 1024,
          stream: true,
          messages: [{ role: "user", content: prompt }],
        }),
        signal: controller.signal,
      });

      const reader = res.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";

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

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop(); // keep incomplete line for next chunk

        for (const line of lines) {
          if (!line.startsWith("data:")) continue;
          const payload = line.slice(5).trim();
          if (payload === "[DONE]") continue;

          try {
            const parsed = JSON.parse(payload);
            const delta = parsed?.delta?.text;
            if (delta) {
              setText((prev) => prev + delta);
            }
          } catch {
            // ignore malformed partial chunks
          }
        }
      }
    } catch (err) {
      if (err.name !== "AbortError") console.error(err);
    } finally {
      setIsStreaming(false);
    }
  }, []);

  const cancel = useCallback(() => {
    controllerRef.current?.abort();
    setIsStreaming(false);
  }, []);

  return { text, isStreaming, send, cancel };
}

Use it in a component:

function ChatBox() {
  const { text, isStreaming, send, cancel } = useClaudeStream();
  const [prompt, setPrompt] = useState("");

  return (
    <div>
      <textarea value={prompt} onChange={(e) => setPrompt(e.target.value)} />
      <button onClick={() => send(prompt)} disabled={isStreaming}>
        Send
      </button>
      {isStreaming && <button onClick={cancel}>Stop</button>}
      <div className="output">{text}</div>
    </div>
  );
}

This gives you a working streaming UI: text appears progressively, there's a cancel button, and the hook cleans up properly if the component unmounts mid-stream.

Things that trip people up

Buffering across chunks. SSE data doesn't arrive aligned to JSON boundaries — a single data: line can be split across two read() calls. The buffer-and-split-by-newline pattern above handles this; skipping it causes intermittent JSON.parse errors in production that are hard to reproduce locally.

Autoscroll. If you're rendering the growing text in a scrollable container, scroll to bottom on every update, but only if the user hasn't manually scrolled up to read earlier content. A simple check on scrollTop vs scrollHeight before forcing a scroll works well.

Markdown rendering mid-stream. If you pipe the streamed text into a markdown renderer on every token, you'll get flickering as incomplete markdown (like an unclosed code fence) gets reparsed. Debounce the render to every 2–3 chunks, or render plain text while streaming and swap to full markdown once the stream finishes.

Cancellation. Users will click away or submit a new prompt before the first one finishes. Always keep an AbortController reference and call .abort() on new requests or unmount — otherwise you get overlapping streams writing into the same state.

Backpressure on slow networks. If the client can't keep up with incoming chunks (rare, but happens on throttled connections), React's state batching can cause the UI to jump rather than animate smoothly. Batching updates every few deltas instead of on every single token reduces re-renders without hurting perceived speed.

Why route through an API layer

Building this directly against raw model access works, but most teams end up needing API keys scoped per application, usage visibility per endpoint, and a way to swap models without touching frontend code. SubToAPI sits between your React app and Claude: you get sub_live_ keys per app, the same streaming behavior shown above, and a dashboard with usage metadata, without managing your own key rotation or billing reconciliation. The quickstart covers authentication, and the streaming docs have the full event reference if you need to handle tool-use deltas or stop reasons inside the same component. Pricing starts at the Solo plan (€9) if you're testing this standalone before plugging it into a larger product — see pricing.

questions

Does streaming require a special API plan or endpoint? No — streaming is just a request parameter ("stream": true) on the same messages endpoint used for non-streaming calls. See /docs/messages for the full request shape.

Can I stream tool use results the same way? Yes, tool-use deltas arrive as separate event types within the same SSE stream. Parse the event type field before reading delta.text, and check /docs/tools for the exact payload structure.

Why does my UI flicker or jump during streaming? Usually it's re-rendering markdown on every token or not batching state updates. Render plain text while streaming and switch to rich markdown rendering once the stream completes, or batch updates every few chunks.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →