# 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>
    ### Map JSON content to a state snapshot

    A .NET agent publishes state as a `DataContent` update with the
    `application/json` media type. The `MapContent` mapping on
    `AGUIStreamOptions` is what turns that content into a `STATE_SNAPSHOT`
    event for the frontend. Register it next to `AddAGUIServer`:

    ```csharp title="Program.cs"
    using System.Text.Json;
    using AGUI.Abstractions;
    using AGUI.Server;
    using Microsoft.Extensions.AI;

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddAGUIServer();
    // Turn the wrapper's JSON DataContent into a STATE_SNAPSHOT event
    builder.Services.Configure<AGUIStreamOptions>(options => options.MapContent(content =>
    {
        if (content is not DataContent { MediaType: "application/json" } data) return null;
        try
        {
            using var document = JsonDocument.Parse(data.Data);
            return [new StateSnapshotEvent { Snapshot = document.RootElement.Clone() }];
        }
        catch (JsonException)
        {
            return null;
        }
    }));
    var app = builder.Build();
    ```

  </Step>
  <Step>
    ### Read and write state in an agent wrapper

    Wrap your agent in a `DelegatingAIAgent`. The state the UI sent arrives on
    the AG-UI request, which `TryGetRunAgentInput` recovers from the chat
    options. To update the UI, yield the new state as JSON `DataContent`:

    ```csharp title="Program.cs (excerpt)"
    internal sealed class StateStreamingAgent : DelegatingAIAgent
    {
        // ...

        protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
            IEnumerable<AIChatMessage> messages,
            AgentSession? session = null,
            AgentRunOptions? options = null,
            [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            // Recover the state sent in the AG-UI request
            JsonElement? currentState = null;
            if (options is ChatClientAgentRunOptions { ChatOptions: { } chatOptions } &&
                chatOptions.TryGetRunAgentInput(out RunAgentInput? input) &&
                input?.State is { ValueKind: JsonValueKind.Object } state)
            {
                currentState = state;
            }

            // ... run the inner agent and build the new state snapshot

            byte[] stateBytes = JsonSerializer.SerializeToUtf8Bytes(
                parsedStateSnapshot,
                this._jsonSerializerOptions.GetTypeInfo(typeof(JsonElement)));

            // Emit state snapshot as DataContent
            yield return new AgentResponseUpdate
            {
                Contents = [new DataContent(stateBytes, "application/json")]
            };
        }
    }
    ```

    For a full agent that does this, see
    [`SharedStateAgent.cs`](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/integrations/ms-agent-dotnet/agent/SharedStateAgent.cs),
    or the
    [SharedStateAgent sample](https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/05-end-to-end/AGUIClientServer/AGUIDojoServer/SharedState/SharedStateAgent.cs)
    in the Agent Framework repository.

  </Step>
</Steps>

1. On the backend, write the value to a key in the [agent state](/react-native/ms-agent-dotnet/shared-state). To stream a tool argument into a state key token by token, see [State Streaming](/react-native/ms-agent-dotnet/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/ms-agent-dotnet/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"]}
/>
