Show streamed completion output as it arrives
Live generated text
AI Tools · Hook
useCompletion is a React hook for text-completion interfaces. It streams provider output, manages completion state, and exposes complete for starting generation.
useCompletion provides a completion value and an imperative complete function for generating text from a prompt. It calls a configurable endpoint, streams the provider's response into the completion state, and can share state between components when they use the same identifier.
const { completion, complete } = useCompletion({ api?: string, id?: string })| Name | Type | Description |
|---|---|---|
api | string = '/api/completion' | API endpoint used to generate text; defaults to /api/completion and accepts a relative path or absolute URL. |
id | string | Unique completion identifier; matching identifiers allow hook instances to share state, while omission generates one randomly. |
BODY | object | Type parameter for additional request-body data passed through hook options or complete. |
complete | (prompt: string, options?: { headers?: Record<string, string> | Headers, body?: BODY }) => Promise<string | null | undefined> | Prompt and optional headers or body used to execute a completion request. |
An object including completion, the complete function, and hook-managed completion UI state such as loading and error state.
import { useCompletion } from '@ai-sdk/react'
export default function Page() {
const { completion, complete } = useCompletion({
api: '/api/completion',
})
return (
<div>
<button onClick={() => complete('Why is the sky blue?')}>
Generate
</button>
<pre>{completion}</pre>
</div>
)
}A React component sends a prompt to the completion endpoint and renders the streamed completion.
Live generated text
Shared interface state
Custom backend routing
The hook exposes completion state and a complete function. Calling complete with a prompt sends the request and returns a promise that resolves to the completion result when generation finishes.
Follow-up: How can two components share the same completion state? Configure both hook instances with the same id, because that identifier links their state.
api selects the endpoint used to generate text, and it defaults to /api/completion. The endpoint may be expressed as a relative path or an absolute URL.
Follow-up: How would you pass request-specific data? Provide a body through the complete function's options or through the hook configuration's supported request options.
The hook streams text completions from the AI provider and updates the UI as new completion text arrives. The current generated text is available through completion.
Follow-up: Which stream formats are supported? The documentation identifies text and data stream parts for useCompletion.
useChatuseObjectTextStreamChatTransportstreamProtocol