Instant Interface Setup with the useChat Hook
Building conversational UI inputs manually requires managing state variables for messages, inputs, fetch loading states, and typewriter streams. The Vercel AI SDK provides the useChat client hook to automate this process.
1. What does useChat Automate?
- Message state management: Tracks conversation history arrays automatically.
- Input bindings: Provides
inputvalue andhandleInputChangeevents for textareas. - Submit handling: Automatically intercepts form submits, calls the target endpoint API, streams the reply, and appends the response.
2. Implementing the React Component
Create your chat workspace component:
// app/chat/ChatPanel.tsx
"use client";
import { useChat } from "ai/react";
export default function ChatPanel() {
// Configures endpoint API (defaults to '/api/chat')
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
api: "/api/chat",
});
return (
<div className="flex flex-col h-[600px] max-w-xl mx-auto p-4 border rounded-2xl bg-white shadow">
{/* 1. Scrollable Message Logs */}
<div className="flex-1 overflow-y-auto space-y-4 mb-4">
{messages.map((message) => (
<div key={message.id} className={`p-3 rounded-lg ${message.role === "user" ? "bg-indigo-600 text-white ml-auto" : "bg-gray-100 text-gray-800"} max-w-sm`}>
<span className="font-bold text-xs uppercase block">{message.role}:</span>
<p className="mt-1 whitespace-pre-wrap">{message.content}</p>
</div>
))}
{isLoading && <div className="text-gray-400 text-sm">AI is writing a response...</div>}
</div>
{/* 2. Text Input Area Form */}
<form onSubmit={handleSubmit} className="flex gap-2">
<input
value={input}
onChange={handleInputChange}
className="flex-1 border p-2 rounded-lg text-sm focus:outline-none"
placeholder="Ask something..."
/>
<button type="submit" className="bg-indigo-600 text-white px-4 py-2 rounded-lg text-sm font-semibold">
Send
</button>
</form>
</div>
);
}3. Configuring the Request Body
If you need to submit custom user parameters (such as userId or selected model keys) alongside your message history, configure the body option property:
const { messages, input, handleSubmit } = useChat({
api: "/api/chat",
body: {
userId: "user_99a823c",
customModelId: "gpt-4o-mini",
},
});Published on Last updated: