State
Use store() when you need persist, devtools or named actions; otherwise a module-scope
signal/computed is the same thing with less ceremony. A store is a convention over signals,
not a second system: every state field is a signal, every derived entry a computed, every action
a function run in batch.
Three levels
- Component state:
stateandderivedinside a component (see reactivity). - Module state: a
signalorcomputedexported from a plain.js/.tsmodule. Any.qxfile that imports it reads it like its own state — no provider tree. - A store:
store({ state, derived, actions, persist, devtools })for shared state with named actions, persistence and an action log.
// count.js — module state
import { computed, signal } from '@qatjs/core'
export const count = signal(0)
export const doubled = computed(() => count() * 2)count statedoubled derived// counter.qx — an imported signal reads (and is tracked) like local state
import { count, doubled } from './count.js'
export default function Counter() {
return <button on:click={() => count.set(count + 1)}>{count} × 2 = {doubled}</button>
}In the JSX and in a function written in the component's body, count is its value and count.set
the signal's; code that setup runs directly reads it as written, count()
(the closure rule).
store()
// cart.js
import { store } from '@qatjs/store'
export const cart = store({
name: 'cart',
state: { items: [] },
// the one place `derived` is a function: it receives the state
derived: { count: (s) => s.items.reduce((n, i) => n + i.qty, 0) },
actions: {
add(s, product) {
const line = s.items.find((i) => i.id === product.id)
if (line) line.qty++
else s.items.push({ ...product, qty: 1 })
},
clear(s) {
s.items = []
},
},
persist: 'local',
})cart state- In a component the store reads as its values and writes with
=, in the JSX and in a function beside it alike:cart.items.length,cart.open = true, and its actions as calls. Code the component's setup runs directly reads a field as the signal it is, called:cart.items(). - Actions receive the state as their first argument and run batched: observers run once per
action. An async action is an ordinary
asyncfunction; only its synchronous part is batched. - State is deep for plain objects and arrays:
line.qty++notifies. A Map or Set in a store is not watched inside (s.tags.set(k, 1)notifies nothing): replace it in the action,s.tags = new Map(s.tags).set(k, 1). (A component'sstate(new Map)in.qxis deep.) - Reading: in
.qx, a store reads like a signal —cart.countis the value,cart.add(p)calls the action,cart.coupon = 'X'writes. In.ts,cart.count()reads the computed andcart.items.set([...])writes;const { items } = carttakes out the underlying signal. persist:'local','session', or any object withgetItem/setItem. The state hydrates when the store is created and is saved on every change, as JSON, underqat:<name>. JSON keeps plain data only: a Map or a Set field comes back as{}. Without anamethe key isqat:store, so give every persisted store a name, or two of them overwrite each other. ADatein the state is aDatewhen it is read back (aMap, aSetand a class are not kept as themselves: JSON has none). With'local', a write by another tab of the app is taken as it happens, so two tabs hold one state. A storage that is refused or full keeps nothing, and the store works.devtools: truelogs every action with a snapshot towindow.__QAT_DEVTOOLS__.log, andwindow.__QAT_DEVTOOLS__.stores[name]()returns the current state.redact: ['token']: those fields' values never leave the page through@qatjs/devtools(snapshot(),report(), the action log): their ids are listed instead (dev).
// cart-button.qx
import { cart } from './cart.js'
export default function CartButton({ product }) {
return <button on:click={() => cart.add(product)}>Add ({cart.count} in cart)</button>
}Large stores: cold
// catalog.js
import { store } from '@qatjs/store'
export const catalog = store({
name: 'catalog',
state: { pages: [] },
cold: { after: 60_000 }, // or `cold: true` (60 s)
actions: {
async fill(s) {
s.pages = await (await fetch('/api/catalog')).json()
},
},
})catalog stateA field of a cold store that nothing has read for after milliseconds goes cold:
- It is written to IndexedDB on the user's device, and the store lets go of it. Nothing bound to it changes, since the page already shows it.
- Its next read brings it back:
- at once, while the browser still holds the value (until the garbage collector clears it);
- else from IndexedDB, asynchronously. Meanwhile the read returns a copy of the field's initial
value,
pending(catalog)(from@qatjs/core/cold) istrue, and what read the field reruns when it is back.
- Rows still referenced elsewhere (a derived's filtered list) come back as the same objects, with what was written to them.
What it saves is measured by node scripts/measure/cold.mjs: a store holding 50 pages of data (50 ×
400 rows), the data's share of the heap after 5 minutes without a read, with cold and without,
on a CPU slowed 4×. The target is 60 % lower; a 25-second run measured 85 % lower, and the full
5-minute run has not been made yet.
Rules:
- Write
coldin thestore({ … })literal: the compiler sees it there. A module with a cold store uses@qatjs/core/cold's store, which behaves the same; @qatjs/store's own bytes do not change. - A field's initial value always stays in memory: fill a large store with an action (a load),
not in
state. - While
pending, replace a field withset()or an assignment (that wins over the restore). A write in place into the stand-in copy is lost, andqatjs devsays so in the console. - Never cold:
- a value IndexedDB cannot clone (functions, DOM nodes);
- a
redactfield (its value never leaves the page); - primitives;
- a store on a server, or in a browser without IndexedDB.
- "Not read" is the rule, not "no subscribers". A store cannot count its readers without a hook the core does not have (D288), and a bound field going cold is harmless: nothing is written.
@qatjs/devtoolsshows a cold field greyed, "in IndexedDB", with its size, without bringing it back.keeppages do not go cold: a kept page's state stays in memory as it is.
A state that changes between deploys: version and migrate
// stores/draft.js
import { store } from '@qatjs/store'
export const draft = store({
name: 'draft',
state: { fullName: '', email: '', address: null },
version: 2,
migrate: { 2: (s) => ({ ...s, fullName: s.name }) },
persist: 'session',
})draft stateA persisted store's saved state outlives the build that wrote it. So does an open session's, which
a live switch hands to the new build. With version, a state saved by an older version is migrated
before the store reads it. The written migrations run in order (migrate[2] turns version 1 into
version 2), then the fields are taken as this version has them: one it no longer has is dropped,
a new one starts at its initial value. The version is saved beside the state.
The build says when a migration must be written. qatjs compress compares each store with the same
store in the builds it keeps (dist/versions.json). It reads the stores it can find: a const x = store({ … }) literal at the top of a .js, .mjs
or .ts file under src/ (exported or not), when it is persisted — in a
live build, every such store. A store in a
.qx file, or one made inside a function, is not compared, so its changes are not checked:
- a field added with a start a missing value can take (
null,0,'',false,[],{}), or a field removed: nothing to write; - a field whose shape changed, a field removed alongside one added (a rename or a split), or a
field added with another start:
QX-STORE-MIGRATION-NEEDED, and the build stops. Raiseversionand write itsmigrate. Nothing is guessed.
A store with version compiles to @qatjs/store/version (442 B over the store), as cold does to
@qatjs/core/cold.
One store per tree: store.scoped
A module-scope store is one global instance — right in the browser. When each subtree needs its own instance (a wizard, a panel opened twice; and on a server, every request), create it in the component that owns the tree and provide it:
// panel.qx
import { store } from '@qatjs/store'
import { Filters } from './tokens.js'
export default function Panel({ children }) {
provide(Filters, store.scoped({ state: { query: '' }, actions: { clear: (s) => (s.query = '') } }))
return <section>{children}</section>
}// search-box.qx — anywhere below the panel
import { Filters } from './tokens.js'
export default function SearchBox() {
const filters = inject(Filters)
return <input bind:value={filters.query} />
}store.scoped(def) creates an instance owned by the calling component: its effects (persistence)
are disposed with it.
What is deliberately absent
No middleware, no undo/redo, no transactions beyond load's mutate. These are recorded non-goals
(additions §4.3): a store is signals plus a naming convention, and staying small is the point.