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
Parameters
The ID of the agent to retrieve. Defaults to
"default".Array of update types to listen for. Controls when the component re-renders.Available values:
UseAgentUpdate.OnMessagesChanged- Re-render when messages changeUseAgentUpdate.OnStateChanged- Re-render when agent state changesUseAgentUpdate.OnRunStatusChanged- Re-render when run status changes
Return Value
Returns an object with the following property:The agent instance with the following key properties and methods:
messages- Array of conversation messagesisRunning- Boolean indicating if agent is currently executingstate- Current agent state objectthreadId- Current conversation thread IDaddMessage(message)- Add a message to the conversationsetState(state)- Update the agent’s statesubscribe(handlers)- Subscribe to agent events
Examples
Adding Messages and Running Agent
Managing Agent State
Selective Re-rendering
Multi-Agent Setup
Agent Lifecycle
TheuseAgent hook handles agent lifecycle automatically:
- Runtime Connection: When a runtime URL is configured, the hook creates a provisional agent while connecting
- Agent Sync: Once connected, the hook returns the real agent from the runtime
- 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
Related
- CopilotChat - Full-featured chat component
- useAgentContext - Provide context to agents
- useFrontendTool - Register tools for agents
