useChat is a Vercel AI SDK React hook for building conversational interfaces. It manages the message list and input, submits chat requests, and updates the UI as responses stream in. This replaces much of the state and streaming logic a custom chat hook would otherwise need. section 3.2.2 section 3.2.3
Connect a chat form
Import useChat from 'ai/react' and call useChat({ api: '/api' }). Render messages, bind an input’s value and onChange to input and handleInputChange, and attach handleSubmit to the form. The hook also exposes isLoading for the streaming chat interface. section 3.2.2 section 3.2.3
The API route supplies the other half of the integration: read messages from the request, pass them to streamText with a selected model, and return a streaming response. Delivering chunks as they arrive lets the conversation update without waiting for the complete answer. section 3.2.3
Send model selections
Keep the selected provider and model in React state, then pass body: { provider, model } to useChat alongside api. The route reads those values, selects a supported model, and streams its response. Because useChat maintains one message list, users can change providers while retaining conversation context. section 3.3.3
Listing 3.6 useChat example
import { useChat } from 'ai/react'; #1
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit} =
useChat({ api: '/api' }); #2
return (
<div>
<Messages data={messages} />. #3
<form onSubmit={handleSubmit}>
<input
value={input}
placeholder="Ask me something..."
onChange={handleInputChange}
/>
</form>
</div>
)
}
A minimal component shows how messages, input, handleInputChange, and handleSubmit connect to a chat form. section 3.2.2
