Claude API Streaming UI: React Components That Work
Building a chat interface that streams Claude's response token-by-token instead of waiting for the full completion is mostly a state management problem, not a networking problem. The hard part isn't opening a connection — it's updating React state fast enough, in the right order, without re-rendering on every single token and tanking performance.
This guide walks through a working streaming UI pattern for Claude: a hook that consumes server-sent events, a component that renders partial text safely, and the gotchas that trip people up (duplicate renders, markdown flicker, abort handling, and stale closures).
Why streaming UIs are different from normal fetch
A normal fetch call resolves once with a full JSON body. Streaming responses from Claude arrive as a sequence of event:/data: lines over an open HTTP connection, and your UI needs to:
- Parse each chunk as it arrives (not wait for the stream to close)
- Append text incrementally to a single message bubble
- Handle the stream being cancelled mid-response (user clicks stop, or navigates away)
- Distinguish "still streaming" from "done" so you can show a cursor, disable the input, etc.
None of this is Claude-specific — the same pattern applies to any SSE-based LLM API, including SubToAPI's /v1/messages endpoint with stream: true, which mirrors the same event shape.
The streaming hook
Keep the parsing logic out of your components. A custom hook that owns the EventSource-style reader and exposes { text, isStreaming, error, stop } is the cleanest separation.
import { useRef, useState, useCallback } from "react";
export function useClaudeStream() {
const [text, setText] = useState("");
const [isStreaming, setIsStreaming] = useState(false);
const [error, setError] = useState(null);
const controllerRef = useRef(null);
const send = useCallback(async (prompt) => {
setText("");
setError(null);
setIsStreaming(true);
const controller = new AbortController();
controllerRef.current = controller;
try {
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
signal: controller.signal,
headers: {
"Authorization": `Bearer ${process.env.NEXT_PUBLIC_SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: prompt }],
}),
});
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\n");
buffer = lines.pop(); // keep incomplete chunk for next loop
for (const line of lines) {
if (!line.startsWith("data:")) continue;
const payload = line.replace("data:", "").trim();
if (payload === "[DONE]") continue;
const event = JSON.parse(payload);
if (event.type === "content_block_delta") {
setText((prev) => prev + event.delta.text);
}
}
}
} catch (err) {
if (err.name !== "AbortError") setError(err.message);
} finally {
setIsStreaming(false);
}
}, []);
const stop = useCallback(() => {
controllerRef.current?.abort();
}, []);
return { text, isStreaming, error, send, stop };
}
Key details that matter:
- Buffer incomplete chunks. SSE lines don't always align with network packet boundaries. Splitting on
\n\nand keeping the trailing fragment prevents JSON parse errors. - Use the functional setState form (
setText(prev => prev + delta)) — otherwise rapid successive updates can read a stale closure value and drop tokens. - Abort cleanly. Catching
AbortErrorseparately avoids showing a scary error message when the user just clicked "stop."
The component
The component layer should be dumb: it renders text, shows a blinking cursor while isStreaming is true, and wires up stop/send.
function ChatMessage({ prompt }) {
const { text, isStreaming, error, send, stop } = useClaudeStream();
useEffect(() => {
send(prompt);
return () => stop();
}, [prompt]);
return (
<div className="message">
<div className="message-body">
{text}
{isStreaming && <span className="cursor">▍</span>}
</div>
{error && <p className="error">{error}</p>}
{isStreaming && <button onClick={stop}>Stop</button>}
</div>
);
}
Don't render markdown on every token. If you're using something like react-markdown, re-parsing the entire string on each delta is a noticeable performance hit once responses get long. Two workable fixes:
- Render plain text while streaming, then re-parse as markdown once
isStreamingbecomesfalse. - Debounce markdown re-parsing to every 60–100ms instead of every token.
Handling tool use and multi-block responses
If your Claude calls include tool use, streamed events will include content_block_start, content_block_delta, and content_block_stop events for multiple blocks (text and tool_use interleaved). Track blocks by index rather than assuming everything is one text stream:
const blocksRef = useRef({});
if (event.type === "content_block_start") {
blocksRef.current[event.index] = { type: event.content_block.type, text: "" };
}
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
blocksRef.current[event.index].text += event.delta.text;
}
This matters if you're building a UI that shows "Claude is using a tool" states alongside streamed text — see /docs/tools for the full event schema and /docs/streaming for the complete event reference if you're going through SubToAPI.
Scrolling and autoscroll behavior
A streaming UI that doesn't autoscroll looks broken. Use a ref on the scroll container and check if the user is already near the bottom before forcing a scroll — otherwise you'll yank control away from someone trying to read earlier text while a response is still streaming in below.
useEffect(() => {
const el = scrollRef.current;
const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 100;
if (nearBottom) el.scrollTop = el.scrollHeight;
}, [text]);
Why route through an API layer instead of the raw provider
If you're calling Claude directly from a client app, you're exposing a long-lived key and you lose per-user usage visibility. Running requests through SubToAPI gives you a scoped sub_live_... key you can actually put behind a backend proxy, plus usage metadata on every response so you can track tokens per user without building your own counter. Streaming, tool use, and the /v1/messages shape work the same way — see /docs/quickstart to get a key and /docs/messages for the full request/response reference. Plans start at €9/month with a free trial at /signup.
questions
Does streaming change how I count tokens for billing? No — usage totals are still returned, just in the final event of the stream rather than a single response body. Sum them the same way you would for a non-streaming call.
Can I cancel a stream mid-response? Yes, using AbortController on the fetch request. Make sure your backend also closes the underlying connection to Claude so you're not billed for tokens generated after the user stopped reading.
Why does my UI flicker or drop characters while streaming? Usually a stale closure in setState or re-parsing markdown on every delta. Use the functional setState form and defer markdown rendering until the stream completes or on a debounce.