State Rendering

Render your agent's state with custom UI components in real-time.


"use client";import React from "react";import {  CopilotKit,  useAgent,  UseAgentUpdate,} from "@copilotkit/react-core/v2";import { DemoLayout } from "./demo-layout";import { useSharedStateStreamingSuggestions } from "./suggestions";interface StreamingAgentState {  document?: string;}export default function SharedStateStreamingDemo() {  return (    <CopilotKit runtimeUrl="/api/copilotkit" agent="shared-state-streaming">      <DemoContent />    </CopilotKit>  );}function DemoContent() {  // Subscribe to BOTH state changes and run-status changes. The former  // drives the per-token document rerender; the latter toggles the  // "LIVE" badge when the agent starts / stops.  const { agent } = useAgent({    agentId: "shared-state-streaming",    updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],  });  useSharedStateStreamingSuggestions();  const agentState = agent.state as StreamingAgentState | undefined;  const document = agentState?.document ?? "";  const isRunning = agent.isRunning;  return <DemoLayout document={document} isStreaming={isRunning} />;}

What is this?#

State rendering lets you build UI that reflects your agent's state in real-time. As your agent progresses through nodes and emits state updates, your frontend renders those changes, showing progress, drafts, or intermediate results.

Free course: See this pattern built end-to-end in Build Interactive Agents with Generative UI — a free DeepLearning.AI short course taught by CopilotKit's CEO covering the full Generative UI spectrum (Controlled, Declarative, and Open-Ended).

When should I use this?#

Use state rendering when you want to:

  • Show real-time progress (e.g. "Researching... 2/5 complete")
  • Display drafts that update as the agent works
  • Build dashboards that reflect agent state
  • Render structured output outside of the chat

How it works in code#

On the frontend, subscribe to the agent's state. Each time the backend forwards a fresh value, your component re-renders with the latest partial output.

page.tsx
  // Subscribe to BOTH state changes and run-status changes. The former  // drives the per-token document rerender; the latter toggles the  // "LIVE" badge when the agent starts / stops.  const { agent } = useAgent({    agentId: "shared-state-streaming",    updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],  });

On the backend, a state-streaming mapping forwards a specific tool argument straight into a state key as it's being generated. Some frameworks provide that as middleware; direct SDK adapters can emit STATE_SNAPSHOT events from their streaming loop. Either way, the UI can watch the answer assemble token-by-token rather than appearing in one burst between checkpoints.