Skip to main content

Overview

useAgent is a React hook for connecting to Agents via WebSocket. It provides real-time state synchronization, typed RPC method calls, and identity management.

Options

UseAgentOptions<State>
required
string
required
Name of the agent class (e.g., “MyAgent” → “my-agent”)
string
default:"default"
Name of the specific Agent instance
string
Full URL path - bypasses agent/name URL construction. Server must handle routing manually (e.g., with getAgentByName + fetch).
string
Additional path to append to the URL. Works with both standard routing and basePath.
QueryObject | (() => Promise<QueryObject>)
Query parameters - can be static object or async function
unknown[]
Dependencies for async query caching
number
default:"300000"
Cache TTL in milliseconds for auth tokens/time-sensitive data (default: 5 minutes)
(state: State, source: 'server' | 'client') => void
Called when the Agent’s state is updated
(error: string) => void
Called when a state update fails (e.g., connection is readonly)
(mcpServers: MCPServersState) => void
Called when MCP server state is updated
(name: string, agent: string) => void
Called when the server sends the agent’s identity on connect
(oldName: string, newName: string, oldAgent: string, newAgent: string) => void
Called when identity changes on reconnect
boolean
default:"true"
Whether the connection should be enabled. Useful for conditional connections.

Return Value

Returns a PartySocket instance extended with:
string
required
The agent class name (kebab-case)
string
required
The agent instance name
boolean
required
Whether identity has been received from the server
Promise<void>
required
Promise that resolves when identity is received
(state: State) => void
required
Update the Agent’s state from the client
(method: string, args?: unknown[], options?: StreamOptions) => Promise<T>
required
Call a method on the Agent via RPC
AgentStub<T>
required
Typed RPC stub for calling Agent methods

Basic Usage

State Synchronization

Typed RPC with Stub

Advanced Usage

Custom Routing with basePath

Async Query Parameters

Conditional Connection

MCP Server Updates

Identity Changes

Streaming RPC

Streaming Text Generation

Connection State

Wait for Ready

Connection Events

Query Caching

Async query results are cached to avoid re-fetching on every render:

Cache Invalidation

  • Cache is invalidated when queryDeps change
  • Cache expires after cacheTtl milliseconds
  • Cache is cleared on connection close (forces re-fetch on reconnect)

Error Handling

RPC Errors

State Update Errors

Best Practices

Extract State to Custom Hook

Memoize Callbacks

Type Safety