Skip to main content
The useAgent hook provides access to a CopilotKit agent instance, allowing you to read messages, manage state, and control agent execution within your React components.

Basic Usage

import { useAgent } from "@copilotkit/react-core";

function MyComponent() {
  const { agent } = useAgent();
  
  return (
    <div>
      <p>Messages: {agent.messages.length}</p>
      <p>Running: {agent.isRunning ? "Yes" : "No"}</p>
    </div>
  );
}

Parameters

agentId
string
The ID of the agent to retrieve. Defaults to "default".
updates
UseAgentUpdate[]
Array of update types to listen for. Controls when the component re-renders.Available values:
  • UseAgentUpdate.OnMessagesChanged - Re-render when messages change
  • UseAgentUpdate.OnStateChanged - Re-render when agent state changes
  • UseAgentUpdate.OnRunStatusChanged - Re-render when run status changes
Defaults to all update types if not specified.

Return Value

Returns an object with the following property:
agent
AbstractAgent
The agent instance with the following key properties and methods:
  • messages - Array of conversation messages
  • isRunning - Boolean indicating if agent is currently executing
  • state - Current agent state object
  • threadId - Current conversation thread ID
  • addMessage(message) - Add a message to the conversation
  • setState(state) - Update the agent’s state
  • subscribe(handlers) - Subscribe to agent events

Examples

Adding Messages and Running Agent

import { useAgent } from "@copilotkit/react-core";
import { useCopilotKit } from "@copilotkit/react-core";

function ChatComponent() {
  const { agent } = useAgent();
  const { copilotkit } = useCopilotKit();
  
  const handleSendMessage = async () => {
    agent.addMessage({
      id: crypto.randomUUID(),
      role: "user",
      content: "Hello, agent!"
    });
    
    await copilotkit.runAgent({ agent });
  };
  
  return (
    <button onClick={handleSendMessage}>
      Send Message
    </button>
  );
}

Managing Agent State

import { useAgent } from "@copilotkit/react-core";
import { useCopilotKit } from "@copilotkit/react-core";

function StateManagement() {
  const { agent } = useAgent();
  const { copilotkit } = useCopilotKit();
  
  const updateState = async () => {
    // Set state on the agent
    agent.setState({ 
      userId: "123",
      preferences: { theme: "dark" }
    });
    
    // State will be passed to the agent on the next run
    await copilotkit.runAgent({ agent });
  };
  
  return (
    <div>
      <p>Current state: {JSON.stringify(agent.state)}</p>
      <button onClick={updateState}>Update State</button>
    </div>
  );
}

Selective Re-rendering

import { useAgent, UseAgentUpdate } from "@copilotkit/react-core";

function MessagesOnly() {
  // Only re-render when messages change
  const { agent } = useAgent({
    updates: [UseAgentUpdate.OnMessagesChanged]
  });
  
  return (
    <div>
      {agent.messages.map(msg => (
        <div key={msg.id}>{msg.content}</div>
      ))}
    </div>
  );
}

Multi-Agent Setup

import { useAgent } from "@copilotkit/react-core";

function MultiAgentComponent() {
  const { agent: defaultAgent } = useAgent();
  const { agent: researchAgent } = useAgent({ 
    agentId: "research-agent" 
  });
  
  return (
    <div>
      <h3>Default Agent</h3>
      <p>Messages: {defaultAgent.messages.length}</p>
      
      <h3>Research Agent</h3>
      <p>Messages: {researchAgent.messages.length}</p>
    </div>
  );
}

Agent Lifecycle

The useAgent hook handles agent lifecycle automatically:
  1. Runtime Connection: When a runtime URL is configured, the hook creates a provisional agent while connecting
  2. Agent Sync: Once connected, the hook returns the real agent from the runtime
  3. Error Handling: If the runtime fails to connect, a provisional agent is returned to keep the app functioning

Best Practices

Use with CopilotChat

The useAgent hook works seamlessly with <CopilotChat>, which handles agent connection and execution automatically. Use useAgent when you need direct access to agent state or want to build custom UI.

Optimize Re-renders

Use the updates parameter to control when your component re-renders. This prevents unnecessary updates when you only need specific agent changes.

Agent State Persistence

Agent state is passed to the agent on each runAgent call. Use setState to maintain context across multiple interactions.

TypeScript

interface UseAgentProps {
  agentId?: string;
  updates?: UseAgentUpdate[];
}

enum UseAgentUpdate {
  OnMessagesChanged = "OnMessagesChanged",
  OnStateChanged = "OnStateChanged",
  OnRunStatusChanged = "OnRunStatusChanged"
}

interface UseAgentReturn {
  agent: AbstractAgent;
}