Skip to main content
The useAgent hook provides a React-friendly way to connect to agents with automatic cleanup, state synchronization, and reconnection handling.

Installation

Basic Usage

Hook Options

UseAgentOptions

string
required
Name of the agent class to connect to. Automatically converted from camelCase to kebab-case for the URL.
string
default:"default"
Name of the specific agent instance.
string
Custom host for the WebSocket connection. Defaults to the current origin.
string
Custom path prefix for the connection URL.
Record<string, string | null> | (() => Promise<Record<string, string | null>>)
Query parameters to send with the connection. Can be a static object or an async function that returns query parameters.
unknown[]
Dependencies array for the async query function. When any dependency changes, the query function is re-executed.
number
default:"300000"
Cache TTL in milliseconds for async query results. Default is 5 minutes (300000ms).
(state: State, source: 'server' | 'client') => void
Callback invoked when the agent’s state is updated. The source parameter indicates whether the update came from the server or was pushed by the client.
(error: string) => void
Callback invoked when a state update fails (e.g., connection is readonly).
(mcpServers: MCPServersState) => void
Callback invoked when MCP server state is updated.
(name: string, agent: string) => void
Callback invoked when the server sends the agent’s identity on connect. Useful when using basePath, as the actual instance name is determined server-side.
(oldName: string, newName: string, oldAgent: string, newAgent: string) => void
Callback invoked when identity changes on reconnect. If not provided and identity changes, a warning will be logged.
() => void
Callback invoked when the WebSocket connection opens.
() => void
Callback invoked when the WebSocket connection closes.
(error: Event) => void
Callback invoked when a WebSocket error occurs.
(message: MessageEvent) => void
Callback invoked when a raw WebSocket message is received.

Return Value

The hook returns a PartySocket instance with additional agent-specific properties and methods:
string
The kebab-case agent name.
string
The agent instance name.
boolean
Whether the client has received identity from the server.
Promise<void>
Promise that resolves when identity has been received from the server. Resets on connection close.
(state: State) => void
Push state updates to the agent.
<T>(method: string, args?: unknown[], streamOptions?: StreamOptions) => Promise<T>
Call a method on the agent.
Proxy
Proxy object for typed method calls.
(data: string | ArrayBuffer | Blob) => void
Send raw WebSocket message.
() => void
Close the WebSocket connection.
() => void
Force reconnection.

Type Safety

Pass your agent class and state type as type parameters for full type safety:

State Management

Receiving State Updates

The onStateUpdate callback receives both the new state and its source:

Pushing State Updates

When you call setState(), your onStateUpdate callback will fire with source: "client" after the agent broadcasts the update.

Async Query Parameters

For authentication tokens or other async data, use an async query function:
1

Query Execution

The query function is called before establishing the WebSocket connection.
2

Caching

The result is cached for the duration specified by cacheTtl (default: 5 minutes).
3

Re-execution

The query is re-executed when:
  • Any value in queryDeps changes
  • The cacheTtl expires
  • The component remounts

Calling Agent Methods

Using call()

Using the Stub Proxy

The stub proxy provides better TypeScript inference and a more natural calling syntax.

Streaming Responses

Handle streaming responses with the onChunk, onDone, and onError callbacks:

Lifecycle Management

Automatic Cleanup

The hook automatically closes the WebSocket connection when the component unmounts:

Manual Reconnection

Force a reconnection with the reconnect() method:

Waiting for Identity

Use the ready promise to wait for the agent to send its identity:

Connection Events

Handle connection lifecycle events with callbacks:
The client automatically reconnects on connection loss. You do not need to manually handle reconnection logic.

MCP Server Updates

Receive updates about MCP server state:

Examples

Real-time Counter

Authenticated Connection

Streaming AI Response

Best Practices

Use Type Parameters

Pass your agent and state types for full type safety and autocomplete.

Handle Reconnection

The hook automatically reconnects. Your onStateUpdate will fire with the latest state on reconnect.

Cache Auth Tokens

Use cacheTtl and queryDeps to optimize auth token fetching.

Clean Up Side Effects

Use useEffect cleanup functions for any side effects triggered by state updates.

See Also

Client SDK Overview

Learn about the full client SDK capabilities

Vanilla JS Client

Use AgentClient in non-React environments