---
title: "useAgent"
description: "React hook for accessing AG-UI agent instances in React Native"
---

## 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.

<Callout type="info">
  Re-exported from `@copilotkit/react-core/v2`. It is identical to the [React (V2) `useAgent`](/reference/v2/hooks/useAgent); only the import path differs.
</Callout>

**Throws error** if no agent is configured with the specified `agentId`.

## Signature

```tsx
import { useAgent } from "@copilotkit/react-native";

function useAgent(options?: UseAgentProps): { agent: AbstractAgent };
```

## Parameters

<PropertyReference name="options" type="UseAgentProps">
  Configuration object for the hook.

<PropertyReference name="agentId" type="string" default='"default"'>
  ID of the agent to retrieve. Must match an agent configured in
  `CopilotKitProvider`.
</PropertyReference>

  <PropertyReference name="updates" type="UseAgentUpdate[]" default="[OnMessagesChanged, OnStateChanged, OnRunStatusChanged]">
    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.

  </PropertyReference>
</PropertyReference>

## Return Value

<PropertyReference name="object" type="{ agent: AbstractAgent }">
  Object containing the agent instance.

  <PropertyReference name="agent" type="AbstractAgent">
    The AG-UI agent instance. See [AbstractAgent documentation](https://docs.ag-ui.com/sdk/js/client/abstract-agent) for full interface details.

    ### Core Properties

    <PropertyReference name="agentId" type="string | undefined">
      Unique identifier for the agent instance.
    </PropertyReference>

    <PropertyReference name="description" type="string">
      Human-readable description of the agent's purpose.
    </PropertyReference>

    <PropertyReference name="threadId" type="string">
      Unique identifier for the current conversation thread.
    </PropertyReference>

    <PropertyReference name="messages" type="Message[]">
      Array of conversation messages. Each message contains:
      - `id: string` - Unique message identifier
      - `role: "user" | "assistant" | "system"` - Message role
      - `content: string` - Message content
    </PropertyReference>

    <PropertyReference name="state" type="any">
      Shared state object synchronized between application and agent. Both can read and modify this state.
    </PropertyReference>

    <PropertyReference name="isRunning" type="boolean">
      Indicates whether the agent is currently executing.
    </PropertyReference>

    ### Methods

    <PropertyReference name="runAgent" type="(parameters?: RunAgentParameters, subscriber?: AgentSubscriber) => Promise<RunAgentResult>">
      Manually triggers agent execution. Resolves with a `RunAgentResult` (`{ result, newMessages }`) once the run finalizes. `result` is the final value of the run and `newMessages` are the messages produced during it.

      **Parameters:**
      - `parameters.forwardedProps?: any` - Data to pass to the agent execution context

      **Example:**
      ```tsx
      const { result, newMessages } = await agent.runAgent({
        forwardedProps: {
          command: { resume: "user response" }
        }
      });
      ```
    </PropertyReference>

    <PropertyReference name="setState" type="(newState: any) => void">
      Updates the shared state. Changes are immediately available to both application and agent.

      **Example:**
      ```tsx
      agent.setState({
        ...agent.state,
        theme: "dark"
      });
      ```
    </PropertyReference>

    <PropertyReference name="subscribe" type="(subscriber: AgentSubscriber) => { unsubscribe: () => void }">
      Subscribes to agent events. Returns cleanup function.

      **Subscriber Events:**
      - `onCustomEvent?: ({ event: { name: string, value: any } }) => void` - Custom events
      - `onRunStartedEvent?: () => void` - Agent execution starts
      - `onRunFinalized?: () => void` - Agent execution completes
      - `onStateChanged?: (state: any) => void` - State changes
      - `onMessagesChanged?: (messages: Message[]) => void` - Messages added/modified
    </PropertyReference>

    <PropertyReference name="addMessage" type="(message: Message) => void">
      Adds a single message to the conversation and notifies subscribers.
    </PropertyReference>

    <PropertyReference name="addMessages" type="(messages: Message[]) => void">
      Adds multiple messages to the conversation and notifies subscribers once.
    </PropertyReference>

    <PropertyReference name="setMessages" type="(messages: Message[]) => void">
      Replaces the entire message history with a new array of messages.
    </PropertyReference>

    <PropertyReference name="abortRun" type="() => void">
      Aborts the currently running agent execution.
    </PropertyReference>

    <PropertyReference name="clone" type="() => AbstractAgent">
      Creates a deep copy of the agent with cloned messages, state, and configuration.
    </PropertyReference>

  </PropertyReference>
</PropertyReference>

## Usage

### Basic Usage

```tsx
import { Text, View } from "react-native";
import { useAgent } from "@copilotkit/react-native";

function AgentStatus() {
  const { agent } = useAgent();

  return (
    <View>
      <Text>Agent: {agent.agentId}</Text>
      <Text>Messages: {agent.messages.length}</Text>
      <Text>Running: {agent.isRunning ? "Yes" : "No"}</Text>
    </View>
  );
}
```

### Accessing and Updating State

```tsx
import { Text, TouchableOpacity, View } from "react-native";
import { useAgent } from "@copilotkit/react-native";

function StateController() {
  const { agent } = useAgent();

  return (
    <View>
      <Text>{JSON.stringify(agent.state, null, 2)}</Text>
      <TouchableOpacity
        onPress={() => agent.setState({ ...agent.state, count: 1 })}
      >
        <Text>Update State</Text>
      </TouchableOpacity>
    </View>
  );
}
```

### Event Subscription

```tsx
import { useEffect } from "react";
import { useAgent } from "@copilotkit/react-native";

function EventListener() {
  const { agent } = useAgent();

  useEffect(() => {
    const { unsubscribe } = agent.subscribe({
      onRunStartedEvent: () => console.log("Started"),
      onRunFinalized: () => console.log("Finished"),
    });

    return unsubscribe;
  }, []);

  return null;
}
```

### Multiple Agents

```tsx
import { Text, View } from "react-native";
import { useAgent } from "@copilotkit/react-native";

function MultiAgentView() {
  const { agent: primary } = useAgent({ agentId: "primary" });
  const { agent: support } = useAgent({ agentId: "support" });

  return (
    <View>
      <Text>Primary: {primary.messages.length} messages</Text>
      <Text>Support: {support.messages.length} messages</Text>
    </View>
  );
}
```

### Optimizing Re-renders

```tsx
import { Text } from "react-native";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-native";

// Only re-render when messages change
function MessageCount() {
  const { agent } = useAgent({
    updates: [UseAgentUpdate.OnMessagesChanged],
  });

  return <Text>Messages: {agent.messages.length}</Text>;
}
```

## 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
- [`useCopilotKit`](/reference/react-native/hooks/useCopilotKit) - Low-level hook for accessing the CopilotKit core instance
- [React (V2) reference](/reference/v2/hooks/useAgent) - The web equivalent this page mirrors
