# State Streaming

> Stream partial agent state to your React Native UI while a tool call is still running.

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

By default, agent state only updates *between* backend checkpoints, so a long tool call (writing a full document, drafting an email) reaches the UI as one burst at the end. In an agent-native app, that feels broken: users expect to watch the output appear.

**State streaming** copies one tool argument into an agent state key while the model writes the argument. Your screen, subscribed with `useAgent`, re-renders on every token.

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

Use state streaming when a tool's output is long-form text or a growing structured value, and you want the user to see it build up in real time. Common shapes:

- A writing agent that produces a document
- A research agent that collects a list of findings
- A planning agent that builds a step-by-step plan

<WhenFrameworkSupports feature="shared-state-streaming" not>

<Callout type="info">
  **Not available on this framework yet.** This framework's showcase doesn't support state streaming. The UI gets the agent's state between checkpoints, which the [Shared State](/react-native/claude-sdk-typescript/shared-state) page covers.
</Callout>

</WhenFrameworkSupports>

## The backend: one streaming state mapping [#the-backend-one-streaming-state-mapping]

<Steps>
  <Step>
    ### Stream partial state updates while Claude responds

    For streaming state, parse the agent's structured deltas as they arrive and
    emit CopilotKit state updates before the final message is complete. This
    branch runs inside the streamed tool-argument handler.

~~~~typescript title="agent_server.ts"
                if (activeToolCallName === "write_document") {
                  const streamedDocument = partialJsonStringProperty(
                    activeToolArgs,
                    "document",
                  );
                  if (
                    streamedDocument !== null &&
                    streamedDocument !== lastStreamedDocument
                  ) {
                    state = { ...state, document: streamedDocument };
                    lastStreamedDocument = streamedDocument;
                    emit({ type: EventType.STATE_SNAPSHOT, snapshot: state });
                  }
                }
~~~~

  </Step>
</Steps>

The backend pattern is always the same: map one streaming tool argument to one shared-state key. Each framework does this in its own way:

- LangGraph Python: `StateStreamingMiddleware` with `StateItem(...)` entries.
- LangGraph TypeScript: `copilotkitCustomizeConfig` with an `emitIntermediateState` mapping.
- Direct SDK adapters: parse partial tool arguments in the streaming loop, and emit `STATE_SNAPSHOT` whenever the mapped value changes.
- LlamaIndex and Pydantic AI: there is no per-token mapping. A backend tool sends a state snapshot after each step or tool call instead (see the setup above).

When the model streams that argument, CopilotKit writes every partial value into shared state before the tool finishes.

<WhenFrameworkSupports feature="shared-state-streaming">

```typescript title="src/app/demos/shared-state-streaming/state-streaming-backend.ts"
import { EventType } from "@ag-ui/core";
import type Anthropic from "@anthropic-ai/sdk";

type StreamingState = {
  document?: string;
};

type ToolDeltaEvent = {
  type: string;
  content_block?: { type: string; name?: string };
  delta?: { type: string; partial_json?: string };
};

export const WRITE_DOCUMENT_TOOL_SCHEMA: Anthropic.Tool = {
  name: "write_document",
  description: "Write a document into shared agent state.",
  input_schema: {
    type: "object",
    properties: {
      document: {
        type: "string",
        description: "The full document text to render in shared state.",
      },
    },
    required: ["document"],
  },
};

function partialJsonStringProperty(source: string, key: string): string | null {
  // Hand-rolled partial-JSON string extraction with no external dependency
  // (mirrors the Python sibling snippet). Reads the current value of a string
  // property from a partial buffer, tolerating truncation mid-value.
  const marker = JSON.stringify(key);
  const keyPos = source.indexOf(marker);
  if (keyPos < 0) return null;
  const colonPos = source.indexOf(":", keyPos + marker.length);
  if (colonPos < 0) return null;
  const valueStart = source.indexOf('"', colonPos + 1);
  if (valueStart < 0) return null;

  const rawChars: string[] = [];
  let escaped = false;
  for (const char of source.slice(valueStart + 1)) {
    if (escaped) {
      rawChars.push("\\" + char);
      escaped = false;
    } else if (char === "\\") {
      escaped = true;
    } else if (char === '"') {
      break;
    } else {
      rawChars.push(char);
    }
  }
  // A buffer truncated mid-escape drops the dangling backslash (matching the
  // Python sibling) so the partial value still parses instead of forcing null.

  try {
    return JSON.parse(`"${rawChars.join("")}"`) as string;
  } catch {
    return null;
  }
}

export function emitStreamingDocumentState(
  event: ToolDeltaEvent,
  tracker: { toolName: string | null; argsJson: string; lastDocument: string },
  state: StreamingState,
  emit: (event: object) => void,
) {
  if (
    event.type === "content_block_start" &&
    event.content_block?.type === "tool_use"
  ) {
    tracker.toolName = event.content_block.name ?? null;
    tracker.argsJson = "";
    return;
  }

  if (
    event.type !== "content_block_delta" ||
    event.delta?.type !== "input_json_delta"
  ) {
    return;
  }

  tracker.argsJson += event.delta.partial_json ?? "";
  if (tracker.toolName !== "write_document") {
    return;
  }

  const streamedDocument = partialJsonStringProperty(
    tracker.argsJson,
    "document",
  );
  if (streamedDocument === null || streamedDocument === tracker.lastDocument) {
    return;
  }

  // Mutate `state` in place but emit a fresh copy each delta, so a consumer
  // that retains a snapshot doesn't see earlier snapshots mutate to the final
  // text as streaming continues. (Mirrors the Python sibling snippet.)
  const snapshot: StreamingState = { ...state, document: streamedDocument };
  state.document = streamedDocument;
  tracker.lastDocument = streamedDocument;
  emit({ type: EventType.STATE_SNAPSHOT, snapshot });
}
```

</WhenFrameworkSupports>

A few things to note:

- The state key must exist in your agent state (`document` in this example).
- The tool and argument names must match the exact tool call the model makes (`write_document.document` here).
- Streamed values are previews. When the step ends, the state the agent saves replaces them, so save the final value when the tool finishes. On CrewAI, LlamaIndex, and Pydantic AI, write the final value to the agent state yourself, or it is overwritten when the step returns.

## The frontend: useAgent and OnStateChanged [#the-frontend-useagent-and-onstatechanged]

The app side is the same as any other [shared-state](/react-native/claude-sdk-typescript/shared-state) subscription: `useAgent` with `OnStateChanged` gives you a live `agent.state`. Add `OnRunStatusChanged` for a "writing" indicator.

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

export function DocumentView() {
  const { agent } = useAgent({ // [!code highlight:4]
    agentId: "default",
    updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
  });
  const document = (agent.state as { document?: string } | undefined)?.document ?? "";

  return (
    <View style={{ padding: 16, gap: 8 }}>
      {agent.isRunning ? <ActivityIndicator /> : null}
      <ScrollView style={{ maxHeight: 320 }}>
        <Text>{document}</Text>
      </ScrollView>
    </View>
  );
}
```

`agent.state.document` is a string that grows on every token, and `agent.isRunning` tells you whether to show the indicator. The `ScrollView` with a `maxHeight` keeps a long document from pushing the rest of the screen away.

If a fast stream re-renders a heavy screen too often, pass `throttleMs` to `useAgent` to batch the updates.

## Try it [#try-it]

Ask the agent to write a short poem. The `document` text grows on your screen while the agent writes. When the run ends, `agent.isRunning` is `false`, so the indicator goes away.

<IntegrationGrid path="shared-state/streaming" exclude={["agno", "agent-spec", "spring-ai", "langroid"]} />
