Skip to content
Agent UI
HooksuseChat

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.

tsx
Messages: 0

Installation

Install the package once, then import useChat from its direct entry point or from the root.

bash
pnpm add @agent-ui/react
tsx
import { 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.

tsx
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.

API reference for this hook
NameTypeDefaultDescription
initialMessagesChatMessage[][]Seed transcript.
onSend(message: string) => Promise<string>—Return the assistant reply. Reject to surface the error state.
messagesChatMessage[]—Returned transcript.
isStreamingboolean—Returned pending flag.
errorstring | 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.
Use it with the rest of the library

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