Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 3 min read

Stop Re-Rendering Every Token: Building a Smooth 60fps AI Streaming Hook in React & TypeScript

If you have built an AI chat interface in React, you have probably written a streaming loop that looks like this: for await (const chunk of stream) { setOutput((prev) => prev + chunk); } It works fine in a toy

If you have built an AI chat interface in React, you have probably written a streaming loop that looks like this:

for await (const chunk of stream) {
  setOutput((prev) => prev + chunk);
}

It works fine in a toy demoβ€”until a fast model streams 100+ tokens per second into a long Markdown document. Suddenly, React is re-rendering your entire message tree 100 times a second, scrolling fights the user, and closing the tab or clicking "Stop" leaves zombie streams mutating unmounted state.

In this guide, we will fix all three issues in under 70 lines of TypeScript using AbortController and requestAnimationFrame batching.

Why Naive Token-by-Token setState Stutters

A 60Hz display only paints once every 16.6ms. If your SSE endpoint emits 6 small chunks within a single 16ms frame, calling setOutput on every chunk triggers unnecessary reconciliation, Markdown re-parsing, and layout recalculations that the user's screen never even has time to paint.

The fix is simple:

  1. Buffer incoming text chunks in a mutable useRef string (zero React re-renders).
  2. Schedule at most one setState flush per browser animation frame (requestAnimationFrame).
  3. Cancel in-flight HTTP streams cleanly using AbortController.

Step 1: The useBatchedStream Hook

Create useBatchedStream.ts:

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

interface UseBatchedStreamResult {
  text: string;
  isStreaming: boolean;
  error: string | null;
  start: (url: string, body: unknown) => Promise<void>;
  stop: () => void;
}

export function useBatchedStream(): UseBatchedStreamResult {
  const [text, setText] = useState("");
  const [isStreaming, setIsStreaming] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const bufferRef = useRef("");
  const rafIdRef = useRef<number | null>(null);
  const abortRef = useRef<AbortController | null>(null);

  const flush = useCallback(() => {
    rafIdRef.current = null;
    setText(bufferRef.current);
  }, []);

  const scheduleFlush = useCallback(() => {
    if (rafIdRef.current === null) {
      rafIdRef.current = requestAnimationFrame(flush);
    }
  }, [flush]);

  const stop = useCallback(() => {
    abortRef.current?.abort();
    abortRef.current = null;
    if (rafIdRef.current !== null) {
      cancelAnimationFrame(rafIdRef.current);
      rafIdRef.current = null;
    }
    setIsStreaming(false);
  }, []);

  const start = useCallback(
    async (url: string, body: unknown) => {
      stop();
      bufferRef.current = "";
      setText("");
      setError(null);
      setIsStreaming(true);

      const controller = new AbortController();
      abortRef.current = controller;

      try {
        const res = await fetch(url, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body),
          signal: controller.signal,
        });

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

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

        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          bufferRef.current += decoder.decode(value, { stream: true });
          scheduleFlush();
        }

        bufferRef.current += decoder.decode();
        if (rafIdRef.current !== null) {
          cancelAnimationFrame(rafIdRef.current);
          rafIdRef.current = null;
        }
        setText(bufferRef.current);
      } catch (err) {
        if ((err as Error).name !== "AbortError") {
          setError((err as Error).message || "Unexpected stream error");
        }
      } finally {
        setIsStreaming(false);
      }
    },
    [scheduleFlush, stop]
  );

  useEffect(() => stop, [stop]);

  return { text, isStreaming, error, start, stop };
}

Step 2: Smart Auto-Scroll That Respects the User

Only auto-scroll when the user is already near the bottom:

const containerRef = useRef<HTMLDivElement | null>(null);

useEffect(() => {
  const el = containerRef.current;
  if (!el) return;
  const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
  if (distanceFromBottom < 80) {
    el.scrollTop = el.scrollHeight;
  }
}, [text]);

Step 3: Why the Final decoder.decode() Call Matters

Multi-byte UTF-8 characters (emojis, Vietnamese, CJK) can split across network packets. Passing { stream: true } tells TextDecoder to buffer trailing partial bytes until the next chunk arrives, and calling decoder.decode() once at the end flushes any remaining bytes cleanly.

Practical Takeaways

  • Cap UI updates to display refresh rate: Buffering in useRef + flushing on requestAnimationFrame cuts React commits by 50–80% on fast streams.
  • Always wire AbortController: Prevents race conditions when users rapidly submit new prompts or click Stop.
  • Guard UTF-8 boundaries: Always pass { stream: true } inside streaming loops.

More AI engineering and Web3 architecture notes on X at @PhuHo420785.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.