---
title: "State and action semantics"
description: "How an action reads the starting state and commits its writes together, with let for intermediate values, then window state, persist and editing a field's value."
modificationDate: "2026-11-30"
---

> ## Documentation index
> Fetch the complete documentation index at: https://exact.expo.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# State and action semantics

<AgentInstructions>

## Submitting feedback

From the app's directory, read `bun exact.mjs feedback status`. Under `never`, keep no note.
Respect `EXACT_FEEDBACK=0` and do not change the policy.

Otherwise record specific, actionable feedback with:
`bun exact.mjs feedback note "Exact docs: https://exact.expo.dev/learn/contract-for-agents/state-and-action-semantics: <what was wrong or missing>"`

The note goes to Expo only as that status allows. Include no secrets or personal data.

</AgentInstructions>

Action reads see the starting state. Writes commit together. They do not provide
imperative read-after-write visibility. Bind intermediate calculations with `let`:

```contract
component App
  state count = 0
  state doubled = 0
  action advance
    let next = count + 1
    count = next
    doubled = next * 2
  view
    button press=advance testId="advance"
      text `${count}/${doubled}` testId="result"
```

The first press yields `1/2`. Writing `doubled = count * 2` instead would use the
old count and yield `1/0`. The same snapshot rule applies inside nested branches
and to locals declared after a state assignment, and a derive read after the
action assigns its input is the starting state's derive. The compiler warns when
a state is read that way (`analyze-read-after-assign`), naming the line that
assigned the slot, but not when a derive is: read the local you assigned. It
also warns of a send and an assignment of one newest-wins mutation on one path
(`analyze-send-assigned`): the assignment forgets the request in flight and keeps
its value, whichever comes first, so a retry hides the old result while
`pending(m)` instead, and a logout sends through a mutation of its own.

A local is immutable, block-scoped, and visible only after its declaration. It
cannot shadow an in-scope name. Two disjoint arms may declare the same local name.
An action can assign only its own writable state/mutation slots, never a prop,
derive, resource value, or arbitrary record field. Replace a record with a copied
record. `send` targets a mutation owned by that component.

Permitted statements: assignment, `let`, `send`, `refresh`, known host command,
a call of an action, `if`/`else` (`else if c` is `else` around one nested `if`),
and option `match`. No loops: compute the list or value with `map`, `filter` or
`sum` and assign it once. No `return`: a value to compute is a `fn` or a derive.
The compiler
infers effects from the body, through its calls; `writes` is a refusal, not an
optional annotation. Use `symbols` when you need the inferred write set.

An action calls an action of its own component, an `action` prop or an injected
action by name with its parentheses (`play()`, `arrive(path)`; a bare `play` is not a
statement), anywhere a statement goes (LLP 1089). The call is
the callee's statements run where it stands, in the same commit: one rollback,
and the callee reads the state the action started with, as every statement does.
A name that is a host command stays the command. Never give an action, an `action`
prop or an inject a host command's name (`close`, `reload`, `setScheme`, `focus`, …)
if you will call it: the call is refused, `syntax-call-ambiguous`, so a host command
added later can't silently take it over. Binding such a name is allowed. A call gives no value; compute
values with `fn`. Write a repeated sequence once and call it:

```contract
component App
  state location = "/"
  state query = ""
  state sel = 0
  action arrive(path: string)
    location = path
    query = ""
    sel = 0
  action openItem(path: string)
    arrive(path)
  action goHome
    arrive("/")
  view
    column
      button press=openItem("/docs") testId="open"
        text location testId="where"
      button press=goHome testId="home"
        text "home"
```

Because the callee sees the starting state, a slot its caller assigned first
is stale behind the call, and the compiler warns of that read as it does in the
action's own body (`analyze-read-after-assign`, naming both frames): `sel = next`
then `follow()`, where `follow` reads `sel`. Pass the value it should see instead:
`follow(next)` for the new one, or a `let` bound before the assignment for the
old one. Two calls that each read and write one slot (`move(1, 0)` then
`move(0, 1)`) are named the same way: both read the starting cell, and the last
write wins. Calls in exclusive branches
(`if k == "ArrowUp" …` then `if k == "ArrowDown" …`) are separate paths.

A derive is not mutable storage, an async effect, or a timer. Derive cycles are
refused. Avoid unnecessary state that can be calculated from existing values.

## Window state and shared settings

Use `state conversation = "" persist window` for a selection that belongs to
one window. The browser keeps it in `sessionStorage`. Reloading the tab restores
it. An independent tab or a link with `target="_blank"` starts fresh. A named
window with an opener initially receives a copy and then keeps its own values.
AppKit and UIKit restore the values when the system restores the window or scene.

## A remembered setting: `persist`

A root `state` that ends in `persist` is kept across launches (LLP 1116 D5), as
SwiftUI's `@AppStorage` or a React `useState` over `localStorage`:

```contract
component App
  state tipPercent = 18 persist
  state units = "C" persist
  action toggleUnits
    units = units == "C" ? "F" : "C"
  view
    button press=toggleUnits testId="units"
      text `${tipPercent}% · °${units}`
```

- Before the first frame the store is read: a kept value of the state's type
  replaces the initializer's. A missing one keeps the initializer's, and so does
  one of another shape (the state's type changed since), which `logs` names
  (`persisted state units: the stored value does not fit string: …`).
- After a commit changes the state, a value within the limit is saved to the page's
  `localStorage` (`exact.state.<name>`), the app's `UserDefaults` domain on Apple
  (never the Keychain), or a file under the app's data directory on Linux. The key
  is the state's name, so renaming the state forgets what was kept.
- Small settings only: a number, string (an `enum<…>` too) or bool, or an option or
  list of one, at most 16 KB as JSON. A kept enum member a later version dropped is
  of another shape: the initializer's value stands. A longer value leaves the last stored value intact, and
  `logs` reports it once until it changes. `persist` on a record, a list of records
  or a state holding an action is `type-persist-type`: keep app data in a source.
  A child component's state is `type-persist-child`; a derive, `syntax-persist-derive`.
- Each authored test starts from an empty store, and its `reload` reads back what
  it kept. A drive with `--storage <name>` keeps persisted state in that store
  between drives (on the web, the next one passes `--keep-storage`; on a native host
  `--reset-storage` empties it); a drive without one starts from the declared values and keeps
  nothing past the drive. The recipe:
  [a remembered setting](https://exact.expo.dev/recipes/persisted-setting.md).

## Editing a value: the field's contract

An `input` handler should update raw draft state on every edit so live search,
validation and button enablement follow typing. A text field fires `change` on
Enter or blur; its handler should normalize the draft. Use `submit` for explicit
submission.

Use a raw draft for a number, date fragment or other value with half-typed
states. This gives the editor three responsibilities:

- **while editing**, the field is bound to raw text in state that `input`
  always writes;
- **validation** reads the parsed value (`parseNumber`, a trim, a length) and
  shows a hint, without touching the text;
- **on commit** (`change`, which a text field fires on Enter and on blur), the
  action writes the accepted value and writes the normalized text back into the
  draft, which changes the binding and redraws the field.
  Since `change` also fires when an edited field loses focus, it is no
  "submit on Return": a form submitting on it submits on a tap away from the
  field (an eye, a "Forgot password?"). Submit on Return with `submit`, which
  runs on Return alone, after the commit (and never for an IME's Return).

For a live filter, assign the accepted text in
`input`, including when it equals the previous value. For example:

```contract
component StockCount
  state digits = "40"
  action edit(v: string)
    digits = v.split("").filter(c => "0123456789".includes(c)).join("")
  view
    input value=digits input=edit inputmode="numeric" aria-label="Stock count"
```

Typing `a` between `4` and `0` leaves the caret between the two digits.
For a length cap alone, use `maxlength=3`. A conditional action that
skips the assignment on rejection leaves the rejected text visible. An
unconditional assignment of a parsed number erases a half-typed `-` or
`1.`. Assigning `v.trim()` removes a trailing space as it is typed.
Keep raw text in a draft and normalize on `change` when those
intermediate states matter.

```contract
component Quantity
  state count = 1
  state draft = "1"
  action edit(text: string)
    draft = text
  action commit(text: string)
    match parseNumber(text)
      case some(n)
        count = max(0, round(n))
        draft = `${max(0, round(n))}`
      case none
        draft = `${count}`
  view
    column gap=8
      input value=draft input=edit change=commit inputmode="numeric" aria-label="Quantity" testId="qty"
      text (match parseNumber(draft) { case some(n) => (n < 0 ? "Must be 0 or more" : ""), case none => "Enter a number" }) testId="qty-hint"
      text `Ordered: ${count}` testId="qty-count"
```

`type "qty" "-2"` leaves `-2` in the field with the hint; `type "qty" key
"Enter"` commits, and the field reads `0`. A checkbox bound to a resource's
field follows the same rule from the other side: it shows the resource's value,
so it snaps back until the save answers and the resource is read again (LLP 1102
§3.16).
