Skip to main content

Overview

useAgentChat is a specialized React hook for building AI chat interfaces with Agents. It’s part of the @cloudflare/ai-chat package and provides message history, streaming responses, and tool calling.

Installation

Options

UseAgentChatOptions
required
string
required
Name of the chat agent class
string
default:"default"
Name of the specific Agent instance
Message[]
Initial message history
(message: Message) => void
Called when a message is complete
(error: Error) => void
Called when an error occurs

Return Value

Message[]
required
Array of chat messages (user + assistant)
string
required
Current input value
(e: ChangeEvent<HTMLInputElement>) => void
required
Handler for input changes
(e: FormEvent) => Promise<void>
required
Handler for form submission
boolean
required
Whether a response is being generated
(message: Message) => Promise<void>
required
Append a message to the chat
() => Promise<void>
required
Reload the last assistant message
() => void
required
Stop the current streaming response
(messages: Message[]) => void
required
Set the entire message history

Basic Usage

Initial Messages

Streaming Responses

Programmatic Messages

Error Handling

Completion Callbacks

Reload Last Message

Clear Chat

Custom Message Rendering

Best Practices

Extract to Custom Hook

Persist Messages

Auto-scroll to Bottom