# 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>
    ### Show the model the state in its instructions

    The page's state arrives with every run as `RunAgentInput.state`, and the
    adapter makes it the run's shared state. It does not reach the prompt by
    itself. Give the agent dynamic instructions that read it with the
    adapter's `shared_state()`, so the model sees the current value on every
    turn, including edits the user made with `agent.setState`:

~~~~python title="shared_state.py"
def with_state(prompt: str) -> Callable[[RunContextWrapper[Any], Agent[Any]], str]:
    """Dynamic instructions: ``prompt`` plus the run's shared state as JSON."""

    def instructions(_ctx: RunContextWrapper[Any], _agent: Agent[Any]) -> str:
        state = shared_state().value
        if not state:
            return prompt
        return (
            f"{prompt}\n\nCurrent shared application state (JSON; the user may "
            f"have edited it since your last turn):\n{json.dumps(state)}"
        )

    return instructions


~~~~

~~~~python title="shared_state.py"
READ_WRITE_PROMPT = (
    "You are a helpful, concise assistant. The shared application state below "
    "has a `preferences` object with the user's name, preferred tone, "
    "language and interests, which the user edits in the app: always respect "
    "them, and address the user by name when you know it. Its `notes` list "
    "holds what you have remembered so far. When the user asks you to "
    "remember something, or when you observe something worth surfacing in "
    "the UI, call `set_notes` with the FULL updated list of short note "
    "strings (existing notes + new)."
)


shared_state_read_write_agent = Agent(
    name="preferences_assistant",
    instructions=with_state(READ_WRITE_PROMPT),
    model=MODEL,
    model_settings=chat_settings(),
    tools=[set_notes],
)


~~~~

  </Step>
  <Step>
    ### Write state from a server tool

    Server tools are ordinary `@function_tool` functions. Inside one,
    `shared_state().update(...)` merges top-level keys into the state and
    streams a `STATE_SNAPSHOT` to the browser before the tool's own result, so
    any component subscribed with `useAgent` re-renders while the agent is
    still running.

~~~~python title="shared_state.py"
@function_tool
def set_notes(notes: list[str]) -> str:
    """Replace the notes array in shared state with the full updated list.

    Use this tool whenever the user asks you to "remember" something, or
    when you have an observation about the user worth surfacing in the
    UI's notes panel. Always pass the FULL notes list (existing notes +
    any new ones), not a diff. Keep each note short (< 120 chars).
    """
    shared_state().update(notes=notes)
    return "Notes updated."


~~~~

    `shared_state().set(value)` replaces the whole state instead. The
    request's own `state` is never changed.

  </Step>
</Steps>

<Callout type="info" title="Inside an OpenAIAgentsAgent run">
  `OpenAIAgentsAgent` sets up `shared_state()` for every request. If you
  drive the SDK yourself with the adapter's translator, start the run inside
  `use_shared_state(SharedState(run_input.state))` and pass the same object
  to `to_agui`.
</Callout>

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