# State Rendering

> Render your agent's state with your own React Native components in real time.

## What is this? [#what-is-this]

State rendering lets you build UI that reflects your agent's state in real time. As your agent works and writes to its state, your app renders those changes: progress, drafts, or intermediate results.

## When should I use this? [#when-should-i-use-this]

Use state rendering when you want to:

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

## How it works in code [#how-it-works-in-code]

<Steps>
  <Step>
    ### Put shared state in the system prompt and tools

    The demo exposes frontend preferences to Claude and gives the agent a tool
    for writing notes back into CopilotKit state. Keep the state contract small,
    typed, and mirrored by the UI components that read the same values.

~~~~python title="shared_state_read_write_agent.py"
SYSTEM_PROMPT = dedent("""
    You are a helpful, concise assistant.

    The user's preferences are supplied via shared state and added at the
    start of every turn — always respect them. Address the user by name
    when known, match the requested tone, and respond in the requested
    language.

    When the user asks you to "remember" something, or you observe
    something worth surfacing in the UI's notes panel, call the
    ``set_notes`` tool with the FULL updated list of short notes
    (existing notes + new ones, not a diff). Keep each note short
    (< 120 characters). After updating notes, briefly acknowledge what
    you remembered.
""").strip()


SET_NOTES_TOOL: dict[str, Any] = {
    "name": "set_notes",
    "description": (
        "Replace the notes array in shared state with the FULL updated "
        "list. Always include every existing note plus any new ones, "
        "not a diff. Keep each note short (< 120 chars)."
    ),
    "input_schema": {
        "type": "object",
        "properties": {
            "notes": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Full list of short note strings to persist.",
            },
        },
        "required": ["notes"],
    },
}


def build_preferences_block(prefs: dict[str, Any] | None) -> str | None:
    """Render the user-supplied preferences as an injectable prompt block.

    Returns ``None`` when no recognised keys are present so the system
    prompt is left untouched.
    """
    if not isinstance(prefs, dict) or not prefs:
        return None
    lines = ["The user has shared these preferences with you:"]
    if prefs.get("name"):
        lines.append(f"- Name: {prefs['name']}")
    if prefs.get("tone"):
        lines.append(f"- Preferred tone: {prefs['tone']}")
    if prefs.get("language"):
        lines.append(f"- Preferred language: {prefs['language']}")
    interests = prefs.get("interests") or []
    if isinstance(interests, list) and interests:
        lines.append(f"- Interests: {', '.join(str(i) for i in interests)}")
    if len(lines) == 1:
        # No recognised fields — don't emit a header with no content.
        return None
    lines.append(
        "Tailor every response to these preferences. Address the user "
        "by name when appropriate."
    )
    return "\n".join(lines)


def _state_dict(state: dict[str, Any]) -> dict[str, Any]:
    """Coerce the AG-UI raw state envelope into the slots we care about."""
    return {
        "preferences": state.get("preferences") or {},
        "notes": list(state.get("notes") or []),
    }


~~~~

  </Step>

  <Step>
    ### Register `set_notes` with Claude

    This dedicated demo uses the Anthropic Messages API directly. Pass the
    schema to `client.messages.stream` so Claude can call `set_notes`.

~~~~python title="shared_state_read_write_agent.py"
        stream_request = client.messages.stream(
            model=normalize_claude_model(
                os.getenv("ANTHROPIC_MODEL", DEFAULT_ANTHROPIC_MODEL)
            ),
            max_tokens=2048,
            system=system,
            messages=messages,
            tools=[SET_NOTES_TOOL],
        )
~~~~

  </Step>

  <Step>
    ### Write the tool result back to shared state

    When Claude calls `set_notes`, replace the notes array, emit a
    `StateSnapshotEvent` for the UI, and return a `ToolCallResultEvent` to
    Claude before the loop continues.

~~~~python title="shared_state_read_write_agent.py"
        # Execute set_notes by mutating shared state and emitting a
        # StateSnapshotEvent so the UI re-renders the agent-authored
        # notes. This is the agent-side half of the WRITE direction.
        tool_results: list[dict[str, Any]] = []
        for tc in tool_calls:
            if tc["name"] == "set_notes":
                notes = tc["input"].get("notes") or []
                if isinstance(notes, list):
                    state["notes"] = [str(n) for n in notes]
                result_text = json.dumps({"status": "ok", "count": len(state["notes"])})
                yield encoder.encode(
                    StateSnapshotEvent(type=EventType.STATE_SNAPSHOT, snapshot=state)
                )
            else:
                result_text = json.dumps({"error": f"unknown tool {tc['name']}"})

            yield encoder.encode(
                ToolCallResultEvent(
                    type=EventType.TOOL_CALL_RESULT,
                    tool_call_id=tc["id"],
                    message_id=f"{msg_id}-tool-result-{tc['id']}",
                    content=result_text,
                )
            )
            tool_results.append(
                {
                    "type": "tool_result",
                    "tool_use_id": tc["id"],
                    "content": result_text,
                }
            )
        messages.append({"role": "user", "content": tool_results})
~~~~

  </Step>

  <Step>
    ### Serve the shared-state loop

    Mount the dedicated runner on `/shared-state-read-write` and return its
    AG-UI events as a streaming response.

~~~~python title="agent_server.py"
@app.post("/shared-state-read-write")
async def shared_state_read_write_endpoint(request: Request) -> StreamingResponse:
    """Bidirectional shared state demo — UI writes preferences, agent writes notes.

    Uses its own streaming loop (not the shared sales-assistant
    ``run_agent``) because the state schema, tools, and prompt-injection
    middleware are all demo-specific.
    """
    body = await request.json()
    input_data = RunAgentInput(**body)

    async def event_stream() -> AsyncIterator[str]:
        async for chunk in run_shared_state_read_write_agent(input_data):
            yield chunk

    return StreamingResponse(
        event_stream(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "X-Accel-Buffering": "no",
        },
    )


~~~~

  </Step>
</Steps>

<Callout type="info">
  This Python route intentionally uses its own Messages API loop. It does not
  use `ClaudeAgentAdapter` or an MCP server.
</Callout>

1. On the backend, write the value to a key in the [agent state](/react-native/claude-sdk-python/shared-state). To stream a tool argument into a state key token by token, see [State Streaming](/react-native/claude-sdk-python/shared-state/streaming).
2. On the frontend, subscribe to the agent's state with `useAgent`. Each time the state changes, your component renders again with the latest value.
3. Read the keys from `agent.state` and render them.

```tsx title="src/ResearchProgress.tsx"
import { Text, View } from "react-native";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-native/headless";

type ResearchState = {
  status?: string;
  draft?: string;
  completed?: number;
  total?: number;
};

export function ResearchProgress() {
  const { agent } = useAgent({ // [!code highlight:4]
    agentId: "researcher",
    updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
  });
  const state = (agent.state ?? {}) as ResearchState;

  return (
    <View style={{ padding: 16, gap: 8 }} accessibilityLiveRegion="polite">
      <Text style={{ fontWeight: "600" }}>
        {state.status ?? (agent.isRunning ? "Working..." : "Idle")}
      </Text>
      <Text>
        {state.completed ?? 0} of {state.total ?? "?"} complete
      </Text>
      {state.draft ? <Text>{state.draft}</Text> : null}
    </View>
  );
}
```

`updates` picks which changes re-render the component. `OnStateChanged` fires on state changes, and `OnRunStatusChanged` fires when a run starts or ends, so `agent.isRunning` stays current. Leave `updates` out to re-render on messages too.

Render it next to your chat, under the same provider. The chat and `ResearchProgress` share one agent:

```tsx title="App.tsx"
import { View } from "react-native";
import { CopilotKitProvider } from "@copilotkit/react-native/headless";
import { CopilotChat } from "@copilotkit/react-native/components";
import { ResearchProgress } from "./src/ResearchProgress";

const runtimeUrl = "http://localhost:8200/api/copilotkit";

export default function App() {
  return (
    <CopilotKitProvider runtimeUrl={runtimeUrl}>
      <View style={{ flex: 1 }}>
        <ResearchProgress />
        <CopilotChat agentName="researcher" />
      </View>
    </CopilotKitProvider>
  );
}
```

To check it, ask the researcher agent to write a report. The status line and the counter change while the agent runs, and the draft grows as the agent updates `draft` in its state.

## Inside the chat [#inside-the-chat]

The rendered `CopilotChat` has no slot for extra content between messages. To show state inside the conversation, build your own chat and add a row for it to your `FlatList` data. See [Headless UI](/react-native/claude-sdk-python/custom-look-and-feel/headless-ui).

## Treat state as untrusted [#treat-state-as-untrusted]

Treat agent state as external data. Validate it before you use it for a privileged action, and don't put secrets in state that is streamed to the device.

<IntegrationGrid
  path="generative-ui/state-rendering"
  exclude={["agno", "agent-spec"]}
/>
