Shared State
CopilotKit provides a powerful shared state layer that enables bidirectional communication between your agents and UI components. Agents can update application state, and your UI automatically reflects these changes in real-time.Overview
The shared state system allows agents to:- Replace the entire application state with a new snapshot
- Apply incremental updates using JSON Patch operations
- Coordinate state changes across multiple agents
- Maintain state consistency throughout the agent execution lifecycle
State Update Tools
Agents have access to two built-in tools for state management:AGUISendStateSnapshot
Replaces the entire application state with a new snapshot. Use this when you need to set or reset the complete state structure.- Initial state setup
- Complete state replacement
- Resetting application state
AGUISendStateDelta
Applies incremental updates to application state using JSON Patch operations. This is more efficient for targeted updates and preserves existing state.| Operation | Description | Example |
|---|---|---|
add | Add a new field or array element | { op: "add", path: "/items/-", value: "new" } |
replace | Update an existing field | { op: "replace", path: "/counter", value: 42 } |
remove | Delete a field or array element | { op: "remove", path: "/items/0" } |
Using State in Your Application
Frontend (React)
Access and react to state changes in your React components using theuseAgentState hook:
Backend (Agent)
The agent receives the current state in the system message automatically:State Manager Implementation
CopilotKit internally uses aStateManager to track state changes per agent, thread, and run:
Key Methods
Get state for a specific run:State Events
The system emits events when state changes occur:STATE_SNAPSHOT Event
Emitted whenAGUISendStateSnapshot is called:
STATE_DELTA Event
Emitted whenAGUISendStateDelta is called:
Multi-Agent State Coordination
When using multiple agents, state is tracked independently per agent:Multi-Agent Architecture
Learn more about coordinating multiple agents with shared state
Example: Task List Agent
Here’s a complete example of an agent that manages a task list using state updates:Best Practices
Use Deltas for Updates
Prefer
AGUISendStateDelta for incremental changes to avoid unnecessary re-renders and maintain better performanceValidate State Shape
Define a TypeScript interface for your state structure to ensure type safety across agents and UI
Keep State Flat
Avoid deeply nested state structures - they’re harder to update with JSON Patch and debug
Use Snapshots Sparingly
Reserve
AGUISendStateSnapshot for initialization or complete resets, not frequent updatesJSON Pointer Path Syntax
JSON Patch operations use JSON Pointer (RFC 6901) for paths:Related Resources
Multi-Agent
Coordinate state across multiple agents
Runtime Middleware
Intercept and modify state updates with middleware
