Streaming Real-Time LLM Responses in Next.js and React Native Without UI Lag
Engineering low-latency streaming AI chat interfaces with OpenAI and Claude, handling network drops, and keeping mobile render threads smooth.
Adding generative AI capabilities to modern web and mobile applications is no longer just about calling an API endpoint and waiting for a static JSON response. Waiting 5 to 10 seconds for a complex LLM output creates a frustrating, sluggish user experience that drives users away.
To build interactive, responsive AI products—such as live technical interview coaching platforms, voice companions, or dynamic advisors—streaming tokens in real-time is essential.
However, streaming on mobile (React Native) presents unique challenges compared to web browsers:
- High-frequency React state updates can overwhelm the mobile JavaScript thread, causing visible frame drops.
- Intermittent mobile network connections frequently drop mid-stream.
- Complex Markdown rendering on every new token can cause aggressive re-layout thrashing.
Here is how I architect high-performance, low-latency streaming AI interfaces across Next.js and React Native.
1. Backend Architecture: Server-Sent Events (SSE) with Async Generators
On the backend (Python FastAPI or Next.js route handlers), use Server-Sent Events (SSE) to forward streaming token chunks directly from LLM providers:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
app = FastAPI()
client = AsyncOpenAI()
async def generate_llm_stream(messages: list):
response = await client.chat.completions.create(
model="gpt-4o",
messages=messages,
stream=True,
)
async for chunk in response:
content = chunk.choices[0].delta.content or ""
if content:
yield f"data: {content}\n\n"
yield "data: [DONE]\n\n"
@app.post("/api/ai/stream")
async def chat_endpoint(payload: dict):
return StreamingResponse(
generate_llm_stream(payload["messages"]),
media_type="text/event-stream"
)2. The Mobile Performance Trap: Avoid Per-Token State Re-renders
In React Native, triggering a setStreamingText(prev => prev + chunk) on every single token (15–30 times per second) forces rapid re-rendering of the entire component tree and recalculates text layouts repeatedly:
[Bad Pattern: Per-Token State Update]
Token ➔ setState ➔ Re-render ➔ Token ➔ setState ➔ Re-render ➔ UI Stutter!The Solution: Batched Micro-Updates with RequestAnimationFrame
Instead of immediate re-renders, buffer incoming tokens into an in-memory mutable ref and flush to the UI state using a throttled requestAnimationFrame loop (e.g., every 50–60ms):
import { useRef, useState, useCallback } from "react";
export function useStreamText() {
const [displayText, setDisplayText] = useState("");
const bufferRef = useRef("");
const frameRef = useRef<number | null>(null);
const appendChunk = useCallback((chunk: string) => {
bufferRef.current += chunk;
if (frameRef.current === null) {
frameRef.current = requestAnimationFrame(() => {
setDisplayText(bufferRef.current);
frameRef.current = null;
});
}
}, []);
const reset = useCallback(() => {
bufferRef.current = "";
setDisplayText("");
if (frameRef.current) cancelAnimationFrame(frameRef.current);
frameRef.current = null;
}, []);
return { displayText, appendChunk, reset };
}This simple architectural shift guarantees that the mobile UI runs at a buttery-smooth 60fps, even when processing rapid token bursts from high-throughput models.
3. Resilient Error Handling & Mid-Stream Disconnections
Mobile devices frequently switch between Wi-Fi and cellular networks, which can terminate persistent HTTP streams abruptly.
To ensure a resilient experience:
- Persist Message Checkpoints: Cache the partial streamed text locally in lightweight state stores (like Zustand or SQLite).
- Exponential Reconnection: If an SSE stream drops before the
[DONE]marker is received, trigger a resume request with the last known token offset or prompt context. - Non-Blocking Fallback: Display a subtle "Reconnecting to stream..." indicator rather than throwing an unhandled exception or blanking out the user interface.
4. Structured Output and Behavioral Analytics
In applications like mock interview coaches or style advisors, the user needs both an immediate streaming narrative response and structured rubric metrics (such as performance scores, grammar ratings, or category breakdowns).
A proven pattern is to stream the conversational feedback first, followed by a delimited JSON metadata block at the tail of the stream:
Here is detailed feedback on your system design answer...
[Tokens stream in real-time]
---METADATA---
{"clarityScore": 92, "architectureScore": 88, "keyImprovement": "Mention caching strategies"}When the client parser detects the delimiter, it parses the JSON asynchronously and animates visual score charts without delaying the user's reading experience.
Looking to Ship Real-Time AI Features?
Whether you're developing AI voice companions, automated feedback engines, or LLM-driven SaaS applications, building reliable streaming experiences requires end-to-end full-stack rigor.
Reach out to discuss your AI product and let's turn your concept into production software.
Building a mobile app or web platform?
I take products from concept to a production release in 4–6 weeks. Let's talk through your goals.