useChat
useChat keeps a transcript and drives the async lifecycle around it. onSend receives the user text and the hook appends the assistant reply. If a send is aborted, the pending reply is dropped and the transcript stays consistent.
useChat ships with a full API table, a copyable example, and accessibility notes.
Installation
Install the package once, then import useChat from its direct entry point or from the root.
pnpm add @agent-ui/reactimport { useChat } from "@agent-ui/react/use-chat";Tailwind CSS v4 users: add @source "../node_modules/@agent-ui/react/src" to the global stylesheet so the library utilities are generated.
Usage
The example below is the same code that renders the preview. Copy it, swap in your own handlers, and ship.
import { ChatShell, useChat } from "@agent-ui/react"; const { messages, isStreaming, error, send, stop } = useChat({ onSend: async (text) => { const res = await fetch("/api/chat", { method: "POST", body: text }); return res.text(); },}); <ChatShell messages={messages} isStreaming={isStreaming} error={error} onSend={send} onStop={stop} />API reference
Every prop useChat accepts, its type, default, and behaviour.
| Name | Type | Default | Description |
|---|---|---|---|
| initialMessages | ChatMessage[] | [] | Seed transcript. |
| onSend | (message: string) => Promise<string> | — | Return the assistant reply. Reject to surface the error state. |
| messages | ChatMessage[] | — | Returned transcript. |
| isStreaming | boolean | — | Returned pending flag. |
| error | string | null | — | Returned last error message. |
| send | (text: string) => Promise<void> | — | Returned send function; ignores empty or concurrent sends. |
| stop | () => void | — | Returned abort function. |
| clear | () => void | — | Returned reset function. |
useChat composes with MessageList, ChatShell, useChat, and the provider compose blocks. Browse the full reference or see all components in the gallery.
10 lines · copy-ready