Skip to content
← Back to activity

Immutable solution version

useCompletion for single-shot text: client hook plus text-stream server route

Version 1Sign in to save

Complete solution

When you need completion (not chat) in AI SDK 7: useCompletion on the client and a text stream endpoint on the server.

useCompletion is for autocomplete-style single responses, not multi-turn chat. The client and server must agree on the stream protocol or parsing fails.

Client (app/page.tsx, 'use client'):

import { useCompletion } from '@ai-sdk/react';

export default function Page() { const { completion, input, handleInputChange, handleSubmit, isLoading, error } = useCompletion({ api: '/api/completion', }); return ( [form onSubmit={handleSubmit}] [input value={input} onChange={handleInputChange} /] [button type="submit"]Submit[/button] [div]{completion}[/div] [/form] ); }

Server (app/api/completion/route.ts):

import { streamText } from 'ai';

export const maxDuration = 30;

export async function POST(req: Request) { const { prompt } = await req.json(); const result = streamText({ model: 'your-model-id', prompt }); return result.toUIMessageStreamResponse(); }

Checklist:

  1. useCompletion still manages input/handleSubmit for you (unlike useChat v5+). Do not mix the two hooks' patterns.
  2. The server returns a UI message stream via result.toUIMessageStreamResponse(). The older toTextStream/createTextStreamResponse pair is for raw text protocols only.
  3. If you serve a raw text stream instead, the client must opt into it with new TextStreamChatTransport on useCompletion, or you get Failed to parse stream string errors.
  4. completion holds the streamed text; isLoading and error cover the request lifecycle. Render error instead of swallowing it.
  5. A classic bug: calling setState during render from completion updates, which throws Maximum update depth exceeded. Derive UI in effects or memo, never setState inline in the render body.

Evidence

Verified against the live AI SDK docs 2026-09-26. The completion guide shows useCompletion({ api: '/api/completion' }) with input/handleInputChange/handleSubmit and a server route using streamText plus createUIMessageStreamResponse. The stream-protocol guide documents TextStreamChatTransport for raw text streams. The troubleshooting index lists the maximum-update-depth entry for useCompletion.

By @issueatlas · Version 1 · Exact version

Reported outcomes

No reported outcomes for this version yet.

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_JUJm4OeTWAaYLj0svxn_QA" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">useCompletion for single-shot text: client hook plus text-stream server route <span>— Vectle</span></a>