In Cloudflare's Agents SDK, how do this.setState() and this.sql differ, and how does agent state reach a React dashboard using useAgent()?
answer
- same SQLite, two interfaces
- persist, broadcast, then notify
- replace, not merge
- clients can push state too
- validateStateChange before saving
basics
~20 ssetState() replaces one JSON state value, saves it to the agent's SQLite and broadcasts it to every connected client; this.sql runs your own queries on the same database and broadcasts nothing. useAgent() receives each broadcast as agent.state.
solid answer
~40 sBoth live in the agent's embedded SQLite, so both survive hibernation. `this.setState(next)` replaces the whole state (spread `this.state` to change one field), persists it, broadcasts it over WebSocket to connected clients, then calls `onStateChanged()`. `this.sql` is a tagged template with bound parameters over your own tables, returning rows synchronously, with no broadcast. In React, `useAgent({ agent: "SupportAgent", name })` from `agents/react` exposes `agent.state` (undefined until the first message), re-renders on each broadcast and calls `onStateUpdate(state, source)`. Sync is two-way: a client's `agent.setState()` reaches the agent too, so guard it with `validateStateChange()`, which can throw before anything is saved, or mark viewer connections read-only with `shouldConnectionBeReadonly()`. Keep state small and put history in SQL.
code
typescript · 29 linesimport { Agent, callable, type Connection } from "agents";
type State = { status: "open" | "waiting" | "closed"; unread: number };
export class SupportAgent extends Agent<Env, State> {
initialState: State = { status: "open", unread: 0 };
onStart() {
this.sql`CREATE TABLE IF NOT EXISTS messages (
id TEXT PRIMARY KEY, author TEXT, body TEXT, at INTEGER)`;
}
@callable()
async addMessage(author: string, body: string) {
this.sql`INSERT INTO messages VALUES (${crypto.randomUUID()}, ${author}, ${body}, ${Date.now()})`;
this.setState({ ...this.state, unread: this.state.unread + 1 });
}
@callable()
async history(limit: number) {
return this.sql`SELECT * FROM messages ORDER BY at DESC LIMIT ${limit}`;
}
validateStateChange(next: State, source: Connection | "server") {
if (source !== "server" && next.status !== this.state.status) {
throw new Error("clients may not change ticket status");
}
}
}go deeper
Recall that setState() saves and broadcasts, this.sql queries your own tables, and useAgent() exposes agent.state that re-renders on each change.
Explain the setState() order (persist, broadcast, onStateChanged), the replace-not-merge rule, JSON serialisation, and when a value belongs in state versus a table.
Show how a client push travels through validateStateChange() and read-only connections, and why onStateChanged() cannot be the gate.
Weigh what the agent broadcasts against what clients fetch on demand, since every byte in state is multiplied by connected viewers on every change.
## Two stores in one database Every agent built on Cloudflare's Agents SDK owns an embedded SQLite database inside its Durable Object. The SDK gives you two ways to use it, and they solve different problems. - **`this.state` and `this.setState()`**: one JSON value per agent, typed by the second generic parameter (`Agent<Env, State>`). The SDK stores it in its own table (`cf_agents_state`), loads it lazily on first access, and **broadcasts it to every connected client** whenever it changes. - **`this.sql`**: a tagged template over the same SQLite database. Values interpolated into the template become bound parameters, the call is synchronous, and it returns an array of rows. You create your own tables, indexes and queries; nothing is broadcast. Both survive hibernation and eviction, because both are on disk. What does not survive is anything you keep in a class field: when the agent sleeps, its memory is gone and the next wake reconstructs the instance. ## How `setState()` behaves `setState(next)` performs three steps in order: 1. It **persists** `next` to SQLite. 2. It **broadcasts** the new state over WebSocket to every connected client (except connections where `shouldSendProtocolMessages` returned `false`). 3. It calls your **`onStateChanged(state, source)`** hook, best-effort, after the broadcast. Points that trip people up: - `setState()` **replaces** the whole state. To change one field you spread the old one: `this.setState({ ...this.state, unread: 0 })`. (Workflows called from an agent have a separate `step.mergeAgentState()` that merges.) - State is stored as JSON. Functions and class instances do not survive; a `Date` comes back as a string, so store ISO strings. - `initialState` applies only when no state has been persisted yet. Without `initialState`, `this.state` is `undefined` for a new agent. - Every change is sent to every client, so a growing array in state costs bandwidth on each update. ## State on the React dashboard On the client, `useAgent()` from `agents/react` opens the WebSocket to `/agents/{class}/{name}` and keeps a reactive `agent.state`: - `agent.state` is `undefined` until the first state message arrives, then re-renders the component on every broadcast. - `onStateUpdate(state, source)` fires with `source` set to `"server"` (the agent changed it) or `"client"` (this client pushed it). - The connection reconnects automatically, and the agent sends its current state on each connection, so no manual re-sync is needed. Sync runs **both ways**. A client may call `agent.setState(...)`; the agent receives it, runs your hooks with `source` set to that `Connection`, persists it and broadcasts it to everyone else. That is convenient for collaborative UIs and dangerous for a support dashboard where a customer's browser must not rewrite the agent's view of their ticket. ## Guarding client writes The SDK gives you two server-side controls: | Control | When it runs | What it does | | --- | --- | --- | | `validateStateChange(next, source)` | Before persistence and broadcast; synchronous | Throwing aborts the update | | `shouldConnectionBeReadonly(connection, ctx)` | When a connection opens | Returning `true` makes that client unable to change state, by `setState()` or by a callable that calls it | `onStateChanged()` is a notification hook, not a gate: by the time it runs, the update is already saved and sent. ## Choosing state or SQL | Keep in `setState()` | Keep in `this.sql` tables | | --- | --- | | What the dashboard renders live: ticket status, unread count, who is typing | The full message history | | Small configuration | Large or growing collections | | Counters that change often | Data you query, filter or join | A support agent therefore writes each message to a `messages` table with `this.sql` and puts only `unreadCount` and `status` in state. The dashboard gets live counters through the broadcast and fetches history on demand through a `@callable()` method that runs a `SELECT ... LIMIT`. ## Why per-agent SQLite matters here Because each instance has its own database inside the same Durable Object, reads and writes from `this.sql` and `setState()` do not cross the network: the data sits beside the code that uses it. There is no shared database to contend for between customers, and one customer's agent cannot accidentally query another's rows. The flip side is that a query across all customers (every open ticket in the company) cannot be answered by one agent's database; that report needs its own store fed by the agents. A useful rule when designing an agent: anything the customer's dashboard must see live goes into state, anything the agent must remember or search goes into its tables, and anything that spans agents goes somewhere shared.
- Why not keep the customer's whole conversation in state so the dashboard always has it?Every `setState()` sends the entire state to every connected client, so a growing message array is re-sent on each change. Storing messages in a table with `this.sql` and exposing a paged `@callable()` query keeps broadcasts to a few small fields.
- What does onStateChanged()'s source argument let you avoid?It is `"server"` when the agent itself called `setState()` and a `Connection` when a client pushed the change. Returning early on `"server"` avoids an infinite loop where the hook updates state, which fires the hook again, and lets you react only to client actions.
- Expecting this.setState({ unread: 0 }) to keep the other state fields.
- Keeping per-customer data in a class field and expecting it after the agent sleeps.
- Validating client updates in onStateChanged(), after they were already saved and broadcast.
- Assuming state only flows from server to browser.
- Storing a growing message array in state that is broadcast on every change.