# 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>
    ### Declare the shared state on your Deep Agent

    A Deep Agent declares its state through middleware. Add your field to a
    state schema, and pass that middleware to the agent together with the
    CopilotKit middleware. This example shares a `language` value.

    <Tabs groupId="agent_language" items={['Python', 'TypeScript']} persist>
      <Tab value="Python">
        ```python title="agent.py"
        from typing import Any, Literal, NotRequired

        from copilotkit import CopilotKitMiddleware, CopilotKitState
        from deepagents import create_deep_agent
        from langchain_openai import ChatOpenAI
        from langchain.agents.middleware import AgentMiddleware

        class AgentState(CopilotKitState):
            language: NotRequired[Literal["english", "spanish"]]

        class LanguageStateMiddleware(AgentMiddleware[AgentState, Any]):
            state_schema = AgentState

        agent = create_deep_agent(
            model=ChatOpenAI(model="gpt-6-luna", reasoning_effort="none"),
            middleware=[
                LanguageStateMiddleware(),
                CopilotKitMiddleware(expose_state=["language"]),
            ],
            system_prompt=(
                "You are a helpful assistant. Current agent state contains "
                "language. Always answer in that language."
            ),
        )
        ```
      </Tab>
      <Tab value="TypeScript">
        ```ts title="agent.ts"
        import { createMiddleware } from "langchain";
        import {
          createCopilotkitMiddleware,
          zodState,
        } from "@copilotkit/sdk-js/langgraph";
        import { createDeepAgent } from "deepagents";
        import { z } from "zod";

        // Define the state as a middleware. The default flows through automatically.
        export const languageStateMiddleware = createMiddleware({
          name: "AgentState",
          stateSchema: z.object({
            language: zodState(z.enum(["english", "spanish"]).default("english")),
          }),
        });

        export const agent = createDeepAgent({
          model: "openai:gpt-6-luna",
          middleware: [
            languageStateMiddleware,
            createCopilotkitMiddleware({ exposeState: ["language"] }),
          ],
          systemPrompt:
            "You are a helpful assistant. Current agent state contains " +
            "language. Always answer in that language.",
        });
        ```
      </Tab>
    </Tabs>

    In TypeScript, `zodState` keeps the field in the AG-UI state snapshots
    that reach the frontend.

  </Step>
  <Step>
    ### Expose the field to the model

    A value the UI writes with `agent.setState` reaches the agent's state, but
    the CopilotKit middleware does not show state to the model by default.
    List the fields the model should see in `expose_state` (`exposeState`),
    and say in the system prompt what they mean. Without the allowlist, the
    run succeeds and the model answers as if the UI had written nothing. Keep
    the allowlist narrow.

  </Step>
  <Step>
    ### Read and write the state in your UI

    Deep Agents has no live demo on this page yet, so the demo code below does
    not show for it. `useAgent` returns the agent, its reactive `state`, and
    `setState`:

    ```tsx title="ui/app/page.tsx"
    import { useAgent } from "@copilotkit/react-core/v2";

    function YourMainContent() {
      const { agent } = useAgent({
        agentId: "sample_agent",
      });

      const language = (agent.state.language as string) ?? "english";

      const toggleLanguage = () => {
        agent.setState({ language: language === "english" ? "spanish" : "english" });
      };

      return (
        // style excluded for brevity
        <div>
          <h1>Your main content</h1>
          <p>Language: {language}</p>
          <button onClick={toggleLanguage}>Toggle Language</button>
        </div>
      );
    }
    ```

  </Step>
</Steps>

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