<!--
Sitemap:
- [rxfy](/index): Typed, normalized, reactive state — built on RxJS
- [Comparison](/comparison): rxfy versus Redux Toolkit, MobX, Jotai, and TanStack Query
- [Agent Skills](/agent-skills): Accurate rxfy context for AI coding assistants
- [Examples](/examples): Runnable apps, from client-only to fully live
- [Changelog](/changelog)
- [Getting Started](/getting-started)
- [Store quickstart](/getting-started/store): Normalized reactive state in a client-only app
- [Framework quickstart](/getting-started/framework): The full stack for a live app
- [Core Concepts](/core-concepts): The ideas rxfy is built on
- [Normalization](/core-concepts/normalization): Store each entity once, reference it by id
- [Late Unwrapping](/core-concepts/late-unwrapping): Unwrap async state at the leaf, not the trunk
- [Server-Side Rendering](/core-concepts/ssr): Dehydrate on the server, hydrate with no refetch
- [rxfy](/rxfy): The core package: atoms, lenses, models, and states
- [createModel](/rxfy/create-model): Typed entities in normalized storage
- [defineState](/rxfy/define-state): Typed, normalized state shapes with fetching and mutations
- [createAtom](/rxfy/create-atom): A reactive cell with synchronous get, set, and modify
- [createLens](/rxfy/create-lens): A two-way view into part of an Atom
- [React Bindings](/react): Hooks and helpers for using rxfy in React
- [useStateData](/react/use-state-data): Fetch, normalize, and subscribe to a query
- [useStatePagedData](/react/use-state-paged-data): Paginated and infinite-scroll lists
- [useModelStore](/react/use-model-store): Subscribe to one normalized entity by id
- [useAtom](/react/use-atom): Two-way binding for any IAtom
- [Pending](/react/pending): Render pending, rejected, and fulfilled UI for any observable
- [usePending](/react/use-pending): The status value behind Pending
- [useObservable](/react/use-observable): Bind a raw Observable to React
- [Live client](/react/live-client): Wire a WebSocket transport into StoreProvider
- [rxfy-server](/framework/server): Bind Drizzle tables, write, and publish live updates
- [defineResource](/framework/server/define-resource): Tie a Drizzle table to an rxfy model
- [createServer](/framework/server/create-server): Wire db, resources, hub, and keyer into a Live object
- [Writes](/framework/server/writes): live.create / live.update / live.delete and touch
- [Live messages](/framework/server/messages): What travels between server and client
- [Grants & live hydration](/framework/server/grants): Hand off an SSR render to a live client
- [createTopicKeyer](/framework/server/create-topic-keyer): Time-windowed HMAC ids for topics
- [createInMemoryHub](/framework/server/hub): The pub/sub backbone
- [rxfy-ws](/framework/ws): The default WebSocket transport
- [createWsServer](/framework/ws/server): Attach a Hub to WebSocket connections
- [createWsClient](/framework/ws/client): The browser transport with reconnect and replay
- [Custom transports](/framework/ws/custom-transport): Bring your own ClientTransport
- [Guides](/guides): Task-focused walkthroughs of common rxfy patterns
- [Build a Todo app](/guides/todo-app): A guided, end-to-end first app
- [Pagination and infinite scroll](/guides/pagination): Load and append pages into one normalized list
- [Live blog](/guides/live-blog): Build a real-time blog: SSR, then live patches and stale badges
-->

# defineState \[Typed, normalized state shapes with fetching and mutations]

`defineState` declares a typed, normalized state shape: fetch params, model fields, and
optional mutations. The result wires automatically into the
[`createModel`](/rxfy/create-model) stores managed by `StoreProvider`.

```ts
import { z } from "zod";
import { defineState, array } from "rxfy";

const todosState = defineState({
  key: "todos", // stable identity for the SSR query cache; omit to opt out of caching
  params: z.object({ filter: z.enum(["all", "active", "done"]) }),
  model: { todos: array(TodoModel) },
  mutations: {
    addTodo: (prev, todo: { id: string; title: string; done: boolean }) => ({
      ...prev,
      todos: [...prev.todos, todo],
    }),
  },
});
```

A `StateDescriptor<TParams, TShape, TMutations>` exposes (note your `params` is stored as
`paramsSchema` and your `model` as `fields`):

```ts
type StateDescriptor<TParams, TShape, TMutations> = {
  key?: string; // SSR query-cache identity; absent ⇒ opts out of caching
  window?: readonly string[]; // param names that slice within a dataset (page, cursor, sort)
  paramsSchema: z.ZodType<TParams>; // the `params` schema, used to validate fetch params
  fields: FieldsMap; // the `model` entries: array(Model) | single(Model) | a zod schema (plain value)
  mutations: TMutations; // the reducers, bound by useStateData
};
```

It's a plain, serializable description — it holds no data and runs no fetch itself.
[`useStateData`](/react/use-state-data) consumes it: it validates params with `paramsSchema`,
normalizes a fetch result through `fields`, and binds `mutations`.

Mutation reducers operate on the full fetch shape (entities). When invoked through
`useStateData`, rxfy denormalizes the current ids into fresh entities, runs the reducer,
and normalizes the result back into model stores and ids. The normalized query shape
(what `data$` emits) is derived from the field map: array fields become `string[]`
(entity keys), single fields become `string`, and [plain value fields](#plain-value-fields)
pass through unchanged with their real type.

## `array` / `single`

Field descriptor helpers that declare whether a `defineState` model field holds an array or
a single item.

```ts
import { array, single } from "rxfy";

const userPageState = defineState({
  params: z.object({ userId: z.string() }),
  model: {
    user: single(UserModel), // one item
    friends: array(UserModel), // array of items
  },
});
```

## Plain value fields

Not every field is a normalized entity. A `model` entry can also be a **bare zod schema** — a
boolean, a primitive, or a plain object — declared inline alongside `array()` / `single()`. These
**plain value fields** are not stored in any [Model](/rxfy/create-model) store: they live in the
query state and pass straight through `data$` with their real value and type, while entity fields
still resolve to ids.

```ts
import { z } from "zod";
import { defineState, array } from "rxfy";

const dashboardState = defineState({
  key: "dashboard",
  params: z.object({ id: z.string() }),
  model: {
    todos: array(TodoModel), // normalized → string[] (ids)
    isOpen: z.boolean(), // plain → boolean (passed through)
    filters: z.object({ q: z.string(), tab: z.enum(["all", "mine"]) }), // plain → { q, tab }
  },
  mutations: {
    setOpen: (prev, open: boolean) => ({ ...prev, isOpen: open }),
  },
});
```

`data$` for this state emits `{ todos: string[]; isOpen: boolean; filters: { q; tab } }` — entity
fields as ids, plain fields as their value. The distinction is structural: an `array()`/`single()`
descriptor carries a model, anything else is treated as a plain value, so a plain object that happens
to contain an `id` is never mistaken for an entity. Plain values are validated against their schema
in development and passed through untouched in production.

:::note
Plain values ride inside the query's value, so a **keyed** state dehydrates them for
[SSR](/core-concepts/ssr) along with its entity ids — keep them JSON-serializable, the same constraint entities
have.
:::

## `window`

For live apps, `window` names the params that slice *within* a dataset — page, cursor, sort —
as opposed to params that select *which* dataset the state shows. Windowed params are excluded
from the state's live invalidation channel, so every page of a list shares one channel and a
server write marks all of them stale at once.

```ts
const postsState = defineState({
  key: "posts",
  params: z.object({ userId: z.string(), page: z.number() }),
  window: ["page"], // pages share one invalidation channel per userId
  model: { posts: array(PostModel) },
});
```

The field is inert in a client-only store — it only affects channel derivation in the
real-time layer. See [state channels and grants](/framework/server/grants) for how the
channel is derived and delivered.
