Live-Streaming Prompt Box with Incremental Reply Rendering
Data Structure DesignModel answerLast updated
Design and code a small front-end component that sends a prompt, renders a streamed reply as it arrives, blocks duplicate sends, supports cancel, and shows loading and error states.
Build a minimal chat-style front-end widget, a stripped-down AI assistant. A user types a prompt and submits it. The assistant's answer must appear progressively, piece by piece, beneath the input, instead of showing up only once the whole reply is ready.
You have a backend endpoint that returns its answer as a stream of text chunks. You decide which transport to assume (fetch with a readable body, Server-Sent Events, or WebSocket) and you must state that assumption. For example: POST /api/chat with body { prompt }, which streams plain-text chunks and then either closes cleanly or errors. You may wrap it in a helper such as streamChat(prompt, { signal }) or read the stream directly in the component.
Requirements
- Show a text input and a submit button.
- On submit, call the streaming endpoint with the prompt.
- Display the reply below the input as each chunk arrives.
- Keep the UI responsive during the stream: the input stays usable and the page does not stutter, even with dozens to hundreds of small chunks over a few seconds.
- Prevent, or cleanly handle, duplicate submissions while a reply is still streaming.
- Show a loading state and an error state.
Scope
- One self-contained component. No router. A global state library is not required, but be ready to say whether you would use one and why.
- Target modern evergreen browsers. Use the framework you know best (React is a fine default).
- Persistence, auth, markdown rendering and multi-turn history are out of scope unless you want to add them. Focus on the streaming render loop.
What to deliver
- The component code (state model, submit handler, stream-reading loop, render).
- A short explanation of your assumed API contract, your state transitions, and how you handle cancellation, cleanup, mid-stream errors and render performance.
- The clarifying questions you would raise (transport and chunk format, cancel support, single-turn vs transcript, what to do with partial text on error, accessibility, Enter-to-submit behavior).
Hints
Hint 1
Model the UI with an explicit status value (idle, loading, streaming, done, error) plus the prompt and the accumulated reply text, so impossible combinations cannot occur.
Hint 2
Read the body with a reader loop and one reused TextDecoder using `{ stream: true }` so multi-byte characters split across chunks decode correctly. Wire an AbortController to both submit and unmount.
Hint 3
Appending to state on every chunk can cause hundreds of re-renders. Buffer chunks in a ref and flush once per animation frame, and guard against stale chunks from an earlier request after a new submit or cancel.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumed contract
POST /api/chat, JSON body{ prompt }, response body is a stream of UTF-8 text chunks.- The stream closes normally on success. A network failure or non-2xx status is an error.
- I wrap it in
streamChat(prompt, { signal, onChunk }), which keeps transport details out of the component. If the backend were SSE or WebSocket, only this helper would change.
State model
Keep a small status enum rather than several independent booleans:
idle -> loading -> streaming -> done, with loading or streaming able to move to error or back to idle (cancel).
State: prompt, reply, status, error. Derive everything else from status:
isBusy = status === "loading" || status === "streaming"- the submit button is disabled when
isBusyor the prompt is blank - the spinner shows only in
loading(waiting for the first byte) - a Stop button shows when
isBusy
This makes illegal states, such as "loading and error at once", unrepresentable.
Stream consumption
async function streamChat(prompt: string, { signal, onChunk }: {
signal: AbortSignal; onChunk: (t: string) => void;
}) {
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt }),
signal,
});
if (!res.ok || !res.body) throw new Error(`Request failed (${res.status})`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) break;
onChunk(decoder.decode(value, { stream: true }));
}
const tail = decoder.decode();
if (tail) onChunk(tail);
}
Reuse a single decoder with stream: true, otherwise a multi-byte character split across two chunks turns into garbage. Flush the decoder at the end.
Component
function ChatBox() {
const [prompt, setPrompt] = useState("");
const [reply, setReply] = useState("");
const [status, setStatus] = useState<Status>("idle");
const [error, setError] = useState<string | null>(null);
const abortRef = useRef<AbortController | null>(null);
const bufferRef = useRef("");
const rafRef = useRef<number | null>(null);
const runIdRef = useRef(0);
const flush = () => {
rafRef.current = null;
const text = bufferRef.current;
bufferRef.current = "";
if (text) setReply(r => r + text);
};
const submit = async () => {
if (status === "loading" || status === "streaming" || !prompt.trim()) return;
abortRef.current?.abort();
const ctrl = new AbortController();
abortRef.current = ctrl;
const runId = ++runIdRef.current;
setReply(""); setError(null); setStatus("loading");
bufferRef.current = "";
try {
await streamChat(prompt, {
signal: ctrl.signal,
onChunk: t => {
if (runId !== runIdRef.current) return; // stale guard
setStatus("streaming");
bufferRef.current += t;
if (rafRef.current == null)
rafRef.current = requestAnimationFrame(flush);
},
});
if (runId === runIdRef.current) { flush(); setStatus("done"); }
} catch (e: any) {
if (e.name === "AbortError" || runId !== runIdRef.current) return;
flush();
setError(e.message ?? "Something went wrong");
setStatus("error");
}
};
const stop = () => { abortRef.current?.abort(); flush(); setStatus("idle"); };
useEffect(() => () => {
abortRef.current?.abort();
if (rafRef.current) cancelAnimationFrame(rafRef.current);
}, []);
// render: form with input + submit/stop, spinner, <div aria-live="polite">{reply}</div>, error + Retry
}
Key decisions and trade-offs
Duplicate submissions. The button is disabled while busy, and the handler also returns early, because Enter key presses or double clicks can bypass a disabled button. Alternative: allow a new submit that aborts the old request. I would pick one policy and state it; "ignore while busy plus an explicit Stop" is the simplest and least surprising.
Cancellation and cleanup. One AbortController per request, aborted on Stop, on a new submit, and on unmount. AbortError is treated as a normal outcome, not an error. A runId guard ensures a late chunk from an old request never writes into the new reply, and nothing calls setState after unmount.
Render performance. Hundreds of chunks mean hundreds of setState calls if done naively. Buffering in a ref and flushing once per animation frame caps updates at about 60 per second, and typically far fewer. Keep the reply in a small isolated component so the input and surrounding tree do not re-render. Rendering as a plain text node is cheap; avoid re-parsing markdown on each chunk (if added later, throttle it). The main thread stays free because reader.read() is awaited asynchronously, so the input remains typeable.
Errors mid-stream. I keep the partial text visible, mark it as interrupted with an error banner, and offer Retry, which resubmits the same prompt. Discarding is the alternative if partial answers are misleading for the product; this is a clarifying question worth asking.
Loading vs streaming. loading covers time to first byte (spinner), streaming begins on the first chunk (blinking cursor or "Stop" button).
Accessibility. Put the reply in an aria-live="polite" region (consider aria-busy during streaming to avoid announcing every token), keep focus on the input, support Enter to submit and Shift+Enter for newline if using a textarea, and use a real <form>.
State management. Local useState plus refs is enough for a single-turn component. I would reach for a reducer if the transitions grow, and for a store or context only when multiple components (transcript, sidebar) need the same data.
Complexity
Each chunk costs O(chunk length) to buffer; appending to the string state is amortized per frame, so total work is roughly linear in response size, with at most about one render per frame.
Common mistakes
- Creating a new
TextDecoderper chunk or omittingstream: true. - Relying only on a disabled button for duplicate protection.
- Not aborting on unmount, leaving a dangling request and a
setStatewarning. - Treating
AbortErroras a user-visible error. - Re-rendering the whole page per token.
- Letting stale chunks from a cancelled request append to a new answer.
- Forgetting to flush the buffered text on completion, error or stop.