useChat
API reference for the useChat hook.
Allows you to easily create a conversational user interface for your chatbot application. It enables the streaming of chat messages from your AI provider, manages the chat state, and updates the UI automatically as new messages are received.
The useChat API has been significantly updated in AI SDK 5.0. It now uses a
transport-based architecture and no longer manages input state internally. See
the migration
guide for
details.
Import
import { useChat } from '@ai-sdk/react'
import { Chat } from '@ai-sdk/svelte'
import { useChat } from '@ai-sdk/vue'
import { Chat } from '@ai-sdk/angular'
API Signature
Parameters
chat?:
transport?:
/api/chat endpoint.api?:
credentials?:
headers?:
body?:
fetch?:
prepareSendMessagesRequest?:
options:
id:
messages:
requestMetadata:
body:
credentials:
headers:
api:
trigger:
messageId:
prepareReconnectToStreamRequest?:
options:
id:
requestMetadata:
body:
credentials:
headers:
api:
id?:
messages?:
messageMetadataSchema?:
dataPartSchemas?:
generateId?:
onToolCall?:
sendAutomaticallyWhen?:
onFinish?:
message:
messages:
isAbort:
isDisconnect:
isError:
finishReason?:
onError?:
onData?:
throttle?:
resume?:
Returns
id:
messages:
id:
role:
parts:
metadata?:
status:
error:
sendMessage:
headers?:
body?:
metadata?:
regenerate:
stop:
clearError:
resumeStream:
addToolOutput:
addToolApprovalResponse:
addToolResult:
setMessages:
React rendering and shared Chat instances
In React, messages, status, and error describe the snapshot for the current render.
The underlying Chat updates as stream chunks are processed. React may batch updates,
and throttle can delay message rendering without delaying stream processing or callbacks.
Status and error updates include the latest messages, so a completed or failed response
is rendered with its final message snapshot.
Each useChat({ chat }) call subscribes independently. Consumers sharing a Chat
can display different message snapshots when they use different throttle intervals.
A functional setMessages updater receives the Chat's latest messages, which may be
newer than the messages in the current render.