---
title: "useAgent"
description: "React hook for accessing AG-UI agent instances"
---
`useAgent` is still supported, but we recommend migrating to [`useAgent`](/reference/v2/hooks/useAgent) from the v2 API (`@copilotkit/react-core/v2`).
## Overview
`useAgent` is a React hook that returns an [AG-UI AbstractAgent](https://docs.ag-ui.com/sdk/js/client/abstract-agent) instance. The hook subscribes to agent state changes and triggers re-renders when the agent's state, messages, or execution status changes.
**Throws error** if no agent is configured with the specified `agentId`.
## Signature
```tsx
function useAgent(options?: UseAgentOptions): { agent: AbstractAgent }
```
## Parameters
Configuration object for the hook.
ID of the agent to retrieve. Must match an agent configured in `CopilotKitProvider`.
Controls which agent changes trigger component re-renders. Options:
- `UseAgentUpdate.OnMessagesChanged` - Re-render when messages change
- `UseAgentUpdate.OnStateChanged` - Re-render when state changes
- `UseAgentUpdate.OnRunStatusChanged` - Re-render when execution status changes
Pass an empty array `[]` to prevent automatic re-renders.
## Return Value
Object containing the agent instance.
The AG-UI agent instance. See [AbstractAgent documentation](https://docs.ag-ui.com/sdk/js/client/abstract-agent) for full interface details.
### Core Properties
Unique identifier for the agent instance.
Human-readable description of the agent's purpose.
Unique identifier for the current conversation thread.
Array of conversation messages. Each message contains:
- `id: string` - Unique message identifier
- `role: "user" | "assistant" | "system"` - Message role
- `content: string` - Message content
Shared state object synchronized between application and agent. Both can read and modify this state.
Indicates whether the agent is currently executing.
Enables debug logging for agent events and execution.
### Methods
Manually triggers agent execution.
**Parameters:**
- `options.forwardedProps?: any` - Data to pass to the agent execution context
**Example:**
```tsx
await agent.runAgent({
forwardedProps: {
command: { resume: "user response" }
}
});
```
Updates the shared state. Changes are immediately available to both application and agent.
**Example:**
```tsx
agent.setState({
...agent.state,
theme: "dark"
});
```
Subscribes to agent events. Returns cleanup function.
**Subscriber Events:**
- `onCustomEvent?: ({ event: { name: string, value: any } }) => void` - Custom events (e.g., LangGraph interrupts)
- `onRunStartedEvent?: () => void` - Agent execution starts
- `onRunFinalized?: () => void` - Agent execution completes
- `onStateChanged?: (state: any) => void` - State changes
- `onMessagesChanged?: (messages: Message[]) => void` - Messages added/modified
**Example:**
```tsx
const { unsubscribe } = agent.subscribe({
onCustomEvent: ({ event }) => {
console.log(event.name, event.value);
}
});
// Cleanup
unsubscribe();
```
Adds a single message to the conversation and notifies subscribers.
**Example:**
```tsx
agent.addMessage({
id: crypto.randomUUID(),
role: "user",
content: "Hello"
});
```
Adds multiple messages to the conversation and notifies subscribers once.
Replaces the entire message history with a new array of messages.
Connects to a streaming agent endpoint. Similar to `runAgent` but uses the `connect()` method for persistent connections.
Detaches from the currently active agent run without aborting it. The run continues in the background but stops updating the local agent state.
Aborts the currently running agent execution. Implementation varies by agent type.
Creates a deep copy of the agent with cloned messages, state, and configuration.
Adds middleware to the agent's execution pipeline. Middlewares can intercept and transform agent runs.
## Usage
### Basic Usage
```tsx
import { useAgent } from "@copilotkit/react-core/v2";
function AgentStatus() {
const { agent } = useAgent();
return (
Agent: {agent.agentId}
Messages: {agent.messages.length}
Running: {agent.isRunning ? "Yes" : "No"}
);
}
```
### Accessing State
```tsx
function StateDisplay() {
const { agent } = useAgent();
return
);
}
```
### Optimizing Re-renders
Control when your component re-renders using the `updates` parameter:
```tsx
import { useAgent, UseAgentUpdate } from "@copilotkit/react-core/v2";
// Only re-render when messages change
function MessageCount() {
const { agent } = useAgent({
updates: [UseAgentUpdate.OnMessagesChanged]
});
return
;
}
```
## Behavior
- **Automatic Re-renders**: Component re-renders when agent state, messages, or execution status changes (configurable via `updates` parameter)
- **Error Handling**: Throws error if no agent exists with specified `agentId`
- **State Synchronization**: State updates via `setState()` are immediately available to both app and agent
- **Event Subscriptions**: Subscribe/unsubscribe pattern for lifecycle and custom events
## Related
- [AG-UI AbstractAgent](https://docs.ag-ui.com/sdk/js/client/abstract-agent) - Full agent interface documentation