# useAgent

> React hook for accessing AG-UI agent instances in React Native

## Overview [#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>

By default it binds to a shared agent from the CopilotKit registry. It can also register a private proxied agent for one thread, which is useful for custom thread switchers and multi-conversation UIs.

**Throws an error** if no agent is configured with the specified `agentId`, or if only part of the thread-scoped option set is provided.

## Signature [#signature]

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

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

For fully headless UI that does not import the built-in chat rendering stack, import the hook from the headless entry:

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

## Parameters [#parameters]

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

<PropertyReference name="agentId" type="string" default='"default"'>
  ID of the agent to retrieve. If omitted, the hook uses the agent of the
  surrounding headless `CopilotChat` or `CopilotChatConfigurationProvider`, then
  `"default"`. The React Native `CopilotKitProvider` does not set an agent ID,
  so outside a chat, pass `agentId` for any agent other than `"default"`.
</PropertyReference>

  <PropertyReference name="threadId" type="string">
    Thread ID for a private proxied agent. Must be passed together with
    `agentId` and `runtimeAgentId`.
  </PropertyReference>

  <PropertyReference name="runtimeAgentId" type="string">
    Runtime-side agent ID to route requests to when registering a private
    proxied agent. Must be passed together with `agentId` and `threadId`.
  </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 name="throttleMs" type="number">
    Throttle interval, in milliseconds, for re-renders triggered by message and
    state changes. Run lifecycle updates still fire immediately. If omitted,
    the hook inherits the provider's `defaultThrottleMs`; if neither value is
    set, updates are unthrottled. Pass `0` to disable provider throttling for
    this hook.
  </PropertyReference>
</PropertyReference>

There are two valid option shapes:

- `useAgent()` or `useAgent({ agentId })`: bind to a shared agent. The thread comes from chat configuration or the agent itself.
- `useAgent({ agentId, runtimeAgentId, threadId })`: register a private local agent under `agentId`, route it to the runtime agent named by `runtimeAgentId`, and pin it to `threadId`.

## Return Value [#return-value]

<PropertyReference name="object" type="{ agent: AbstractAgent; isReady: boolean }">
  Object containing the agent instance and its readiness signal.

  <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 [#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 AG-UI conversation messages. Each message contains:
      - `id: string` - Unique message identifier
      - `role: "user" | "assistant" | "system" | "developer" | "tool" | "activity" | "reasoning"` - Message role
      - `content` - Message content. Usually a string. User and tool messages can hold an array of content parts, an assistant message that only calls tools can omit it, and an activity message holds an object
    </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 [#methods]

    <PropertyReference name="runAgent" type="(parameters?: RunAgentParameters, subscriber?: AgentSubscriber) => Promise<RunAgentResult>">
      Low-level: sends a run to the agent and 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.

      For a normal run, call `copilotkit.runAgent({ agent })` from [`useCopilotKit`](/reference/react-native/hooks/useCopilotKit). It takes the same `forwardedProps` and resolves with the same `RunAgentResult`. `agent.runAgent()` does not:

      - send your registered frontend tools or context
      - run frontend tool calls
      - start follow-up runs

      Unlike `agent.runAgent()`, `copilotkit.runAgent()` does not reject when the run itself fails. The core reports the error (code `AGENT_RUN_FAILED`) to its error subscribers and resolves with `{ result: undefined, newMessages: [] }`.

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

      To answer an interrupt, use [`useInterrupt`](/reference/react-native/hooks/useInterrupt). It resumes the run for you. To resume by hand, pass the standard `resume` array with the id of the interrupt that the paused run reported: `copilotkit.runAgent({ agent, resume: [{ interruptId: interrupt.id, status: "resolved", payload }] })`. If your agent emits an `on_interrupt` custom event, resume it with `forwardedProps: { command: { resume } }`.

      **Example:**
      ```tsx
      const { copilotkit } = useCopilotKit();

      const { result, newMessages } = await copilotkit.runAgent({
        agent,
        // Any data your agent reads from the run input.
        forwardedProps: { source: "refresh-button" },
      });
      ```
    </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, messages, agent }) => void` - State changes
      - `onMessagesChanged?: ({ messages, state, agent }) => 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 name="isReady" type="boolean">
    Whether `agent` is the real, runtime-synced agent rather than a provisional
    stand-in returned while the runtime is still connecting, or after it has
    failed to connect.

    `agent` is always a fully-constructed instance, so calling its methods is
    always safe. While `isReady` is `false`, the instance is a placeholder that
    is swapped for the real agent once the runtime finishes syncing. At that
    point `agent` changes reference and dependent effects re-run. Guard on
    `isReady` when you only want to act against the real agent, e.g. subscribing
    to run-lifecycle events you don't want to miss during the provisional
    window.
  </PropertyReference>
</PropertyReference>

## Usage [#usage]

### Basic 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 [#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 [#event-subscription]

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

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

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

    return unsubscribe;
  }, [agent, isReady]);

  return null;
}
```

### Multiple Agents [#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>
  );
}
```

### Thread-scoped Agent [#thread-scoped-agent]

Use the thread-scoped form when one runtime agent needs multiple independent frontend instances, for example one per open conversation. The local `agentId` must be unique in the current provider.

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

function ThreadPreview({ threadId }: { threadId: string }) {
  const { agent, isReady } = useAgent({
    agentId: `preview-${threadId}`,
    runtimeAgentId: "support",
    threadId,
    throttleMs: 100,
  });

  if (!isReady) return <Text>Loading...</Text>;

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

### Optimizing Re-renders [#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 [#behavior]

- **Automatic Re-renders**: Component re-renders when agent state, messages, or execution status changes (configurable via `updates` parameter)
- **Optional Throttling**: Message and state update re-renders can be throttled with `throttleMs` or the provider's `defaultThrottleMs`.
- **Readiness**: While the runtime is connecting, `agent` is a fully-constructed provisional stand-in and `isReady` is `false`; once the runtime syncs, `agent` swaps to the real instance and `isReady` becomes `true`. Guard on `isReady` for work that must target the real agent (e.g. one-time subscriptions)
- **Error Handling**: Throws error if no agent exists with specified `agentId`
- **Thread Scoping**: `threadId` and `runtimeAgentId` must be passed together with an explicit local `agentId`; partial combinations throw at runtime and are rejected by the TypeScript type.
- **State Synchronization**: State updates via `setState()` are immediately available to both app and agent
- **Event Subscriptions**: Subscribe/unsubscribe pattern for lifecycle and custom events
