Reactivity
Setup runs once
A component is a function that runs exactly once per instance. It creates state, wires DOM nodes to it, and returns. When state changes, only the nodes (and effects) that read it update. There is no re-render, so there is nothing to memoize and no dependency array to get wrong.
The primitives
.qx |
Runtime | Meaning |
|---|---|---|
let x = state(v) |
signal(v) |
a value you can write |
let y = derived(expr) |
computed(() => expr) |
a value computed from others; lazy, cached |
effect(() => …) |
effect(fn) |
runs after mount and again when what it read changes |
watch(a, (now, before) => …) |
watch(() => a, fn) |
runs only when a changes, never initially |
mount(() => …) |
onMount(fn) |
runs once, after the component's DOM is in the document |
unmount(() => …) |
onCleanup(fn) |
runs once, when the component goes away |
derived and watch take the expression itself; the compiler makes the getter. An arrow there
(watch(() => a, fn), derived(() => a + b)) would watch or hold a function, so it is an error,
QX-ARROW-SOURCE, whose fix-it is the expression. (.tsx writes the getters out: see tsx.md.)
Reads are tracked automatically: whatever a derived, effect or DOM binding reads during its run
becomes its dependency, and dependencies are re-collected on every run (so cond ? a : b depends on
a or b, never both).
Updates are glitch-free: a derived recomputes at most once per change and only if someone
reads it, and effects run after every derived has settled. Writes inside batch() (and inside
store actions) notify once, at the end.
Equality is Object.is: writing the same value does nothing.
A derived value that reads itself — alone, or through the values it reads — throws where it is
read: qat: a derived reads what reads it. Two that need each other are one value, or one of
them is a state an effect writes.
The closure rule
This is the single most important rule for correct Qat code.
let count = state(0)
const log = () => console.log(count) // reads count LIVE, at call time
setTimeout(log, 1000) // logs the value one second from now
track(count) // passes the current VALUE (a number)
track(ref(count)) // passes the signal itself, so track() can read it latercount state- A
state/derivedvariable used inside a closure (arrow function, callback, event handler) is read when the closure runs. There are no stale closures. - A
state/derivedvariable used as an argument passes its current value. ref(x)passes the underlying signal (a function: call it to read,.set(v)to write).
What is imported, and what a call gave
A signal or a store need not be declared with state in the file: it is imported
(import { session } from './session.js'), or a call gave it (const { cart } = useStores(),
const q = query('q', '')). In the JSX, and in a function written in the component's body — a
handler with a name, a helper — such a name reads as a state does:
import { count } from './count.js'
export default function Counter() {
const q = query('q', '')
const { cart } = useStores()
const add = () => {
count.set(count + 1) // `count` is its value; `count.set` is the signal's
if (q) cart.open = true // `q` is its value; a store's field is read and written by name
}
return <button on:click={add}>{count}</button>
}- the name alone is the value;
x.set(v),x.update(fn),x()andref(x)are the signal; - a plain
let(or a constant that is a literal, an arrow, a function) is a variable, as written; - code that setup evaluates directly — not inside a function, not in the JSX — reads an import as
written:
const first = count(). It runs once; nothing there would re-read.
x.set(v) returns v, as an assignment does: const next = count.set(count + 1).
Deep state
state(v) is deep when v is a plain object, an array, a Map or a Set: nested reads are
tracked per path and nested writes notify only the readers of that path. Anything else (class
instances, Date, DOM nodes, functions) makes a plain signal that notifies when replaced.
let todos = state([{ text: 'milk', done: false }])
todos[0].done = true // re-runs only what read todos[0].done
todos.push({ text: 'eggs' }) // in place; notifies `length` and the new index
todos = [] // replaces the whole value; everything that read todos updatestodos stateRules:
- Deep means plain objects (
{}orObject.create(null)), arrays, andMap/Setinstances (not subclasses). Frozen objects are never proxied. (Map/Set support is a separate entry point,@qatjs/core/deep/collections; the compiler loads it when astatestarts as a Map or Set. In plain JS,import '@qatjs/core/deep/collections'.) - Proxies are cached: the same object always yields the same proxy, nested values become proxies
lazily when read, and
raw(p)returns the object behindp(raw(p) === raw(p2)whenever they wrap the same object). - Tracking is path-level: an
effectreadinglist[3].namere-runs only whenlist[3].name, the elementlist[3], orlistitself changes. - Array methods (
push,pop,shift,unshift,splice,sort,reverse,fill,copyWithin) mutate in place and notify once, at the end of the call. Calling them inside aneffectdoes not make the effect depend on the array. - Iteration (
for…of,map,filter,Object.keys, a Map's or Set's iterators andforEach,size) depends on the key set and reads every element, so it re-runs when anything is added, removed or replaced.map.get(k),map.has(k),set.has(v)and'k' in objdepend on that one key. - Writing an
Object.is-equal value notifies nothing. - Assigning
x = valuereplaces the whole value; a new proxy wraps the new object. - Storing a proxy into another stores the plain object (no proxy-in-proxy); reading it back gives the proxy again.
- Writes made through
raw(x)are not tracked — use it only to hand data out. JSON.stringify(x)works on proxies.structuredClone,postMessageand libraries that mutate or compare identities needraw(x).
State that starts empty
Whether a value is proxied is decided by what can be stored in it, and the compiler decides that at compile time from the initializer and the type argument:
let n = state<number | null>(null) // 1. only primitives fit: a plain signal, no proxy code at all
let user = state<User | null>(null) // 2. an object type: writes go through deep()
let picked = state(null) // 3. untyped: also deep-capable, to be safen stateuser statepicked state- A type argument made only of primitive and literal types (
number | null,'a' | 'b',string) compiles to a plain signal; writes are stored as they are and the file does not load@qatjs/core/deep. - An object (or array, Map, Set) type is deep-capable: the signal starts plain and every object
written into it is proxied, so
user = { name: 'x' }; user.name = 'y'updates the UI. - Without a type argument the compiler cannot know what will be stored, so it is deep-capable too.
That is correct but not free: in the js-framework-benchmark app (
benchmarks/js-framework-benchmark, measured when the.qxversion was written, not repeated since),let selected = state(null)holding a row id made "select row" 1.17–1.47× Solid's time and the bundle 1.4 kB larger; typed asstate<number | null>(null)it was 0.81× Solid's again. Type the empty state when it holds primitives.
An empty array needs a type under strict TypeScript: [] alone is never[], so
let items = state([]); items.push(todo) is a type error in qatjs check ("not assignable to
parameter of type 'never'"). Give the type argument, state<Todo[]>([]) (a JSDoc cast does not
reach it). A large list is usually shallow:
let rows = shallow<Row[]>([]) // the idiom for a list you replace rather than mutate
let tags = state<string[]>([]) // a deep list you push intorows statetags stateshallow
let rows = shallow(bigList) is a plain signal: it notifies only when you assign a new value, and
its elements are never proxied. (In plain JS this is simply signal(bigList).) Use it for large lists (more than ~1,000 items) and for anything you
hand to third-party libraries.
Ownership and cleanup
Everything reactive belongs to the component (or block branch, or list row) that created it. When
that goes away, its effects, watches, derived values, timers registered with unmount, and
in-flight load requests are disposed — children first, then the parent, each in reverse order of
creation. You never unsubscribe by hand.
A function named use… is one a component's setup calls — what React calls a custom hook:
function useMouse() { … }, in the component's file or in a .ts beside it. An effect or a
watch written in it belongs to the component that called it. In any other nested function (a
handler, a callback) they are refused: nothing would own them.
Two limits, both of code that is wrong or unusual. An effect that writes what it reads runs
again without end: it is stopped after a million runs in one flush, with an error that says
what to do, in a build as in qatjs dev. And a chain of derived values each
reading the one before — a running total down a list — may be as long as the list: a change at
its start reaches its end in a loop, not a call per link. What stays a call per link is a
chain's first evaluation from its far end (nothing is known yet of what each link reads): past
a few thousand links that exceeds the stack, reported like any error of a derived. Read in order
— as rows are rendered — it never is that deep.
Lifecycle guarantees
setup (1×) → mount (DOM attached, before paint) → effects/watch → unmount (reverse order)- Setup runs exactly once per instance.
- Parent setup → children setup (in tree order) → children mount → parent mount. A parent's
mountsees its children's DOM. mountruns synchronously right after the DOM is inserted into the document — before paint.effectruns once after mount, then whenever its dependencies change; its cleanup runs before each re-run and on unmount.watchdoes not run initially and receives(now, before).- There is no component-level update phase.
- Unmount disposes everything in reverse order;
loadrequests are aborted; event listeners need no cleanup (they are delegated). - Setup cannot be async — use
load. keep(router, tabs) preserves an instance: its state, scroll position and form values survive navigating away and back.transition:fade/transition:slide={{ duration: 300 }}animate in on insert; leaving waits for the animation before removing the node.
Each guarantee is a test in packages/qat/test/lifecycle.test.ts.
Large lists
A {for} creates every row in one go. For lists in the thousands:
chunked(list, n)renders the firstnitems at once andnmore per background task:{for (const row of chunked(rows, 500))}keeps each task's script short (creating 10,000 rows: under 8 ms per task, against ~30 ms in one go). Keys work as in a plain{for}.- The layout side is CSS. Each new chunk makes the browser restyle and lay out the list again;
for a 10,000-row striped table that alone is 70–100 ms per frame, whatever the script does.
content-visibility: autowithcontain-intrinsic-sizeon block-level rows lets the browser skip off-screen rows, and avoiding:nth-child/:nth-of-typestriping avoids restyling every row on each append. <VirtualList>(@qatjs/ui, copied into your app) keeps only the visible rows in the DOM at all: the answer for very large or endless data. It is arole="list"named by itslabelprop, scrolls by keyboard (it takes focus), and its rows carryaria-posinset/aria-setsize, so a screen reader still says "501 of 10,000".
Large collections
A derived already knows which derived to recompute. Over a large collection it can also know
what inside it to recompute: one element changed, so only that element's part of the chain runs
again.
// report.qx
import { sortBy, sum } from '@qatjs/core/collections'
export default function Report() {
let rows = state<Row[]>([]) // a deep store, filled by a load or a store action
let total = derived(rows.filter((r) => r.qty > 0).map((r) => r.price * r.qty).reduce(sum, 0), { incremental: true })
let cheapest = derived(sortBy(rows.filter((r) => r.open), (r) => r.price), { incremental: true })
return <p>{total} · {cheapest[0]?.name}</p>
}rows statetotal derivedcheapest derivedThe chain. It reads a deep store collection (a state([...]), or a path into one). It then
has filter, map and sortBy stages in any order, and at most one end: length, reduce,
find, some, every or groupBy. sortBy(xs, key) and groupBy(xs, key) come from
@qatjs/core/collections, with the reducers sum, count and avg (xs.reduce(sum, 0)). They are plain
functions anywhere; in a chain the compiler recognizes them.
Delta mode. With { incremental: true }, or when the collection is known large (a
state(static(…)) of 500 elements or more), the compiler proves the callbacks pure:
- each callback is written in place;
- it takes one parameter (a reducer, two): the index would change with every insertion;
- it reads only its element, its own locals, signals, constants and pure built-ins (
Math.*butrandom, string and array methods that do not mutate); - it writes nothing outside itself.
The chain then compiles to incremental(…) from @qatjs/core/collections/delta.
What one change costs.
- A changed element reruns that element's callbacks, plus a scan of √n records to find it.
- Then each stage forwards only that change:
- a filter: the element entered, left, stayed or changed;
- a map: the element's value;
sortBy: one remove and one insert;sum,count,avgand a literal(a, b) => a + b: an inverse;max,minand other reducers: the records folded again, without rerunning a callback.
- On a 10,000-row report, one price change costs about 0.02 ms against about 3 ms for the chain
as written (
node scripts/measure/collections.mjs: 0.018 ms against 2.87 ms in a short run; its full timed run is still to be made). - A signal read inside a callback (
r.price > threshold) reruns every element when it changes. That is the chain as written.
What stays the same.
- The first computation runs the chain as written, so a page rendered once (on a server) costs what it did.
- The next computation builds the per-element graph, once. It costs about 2–3 times one run of the chain, and the graph holds about as much memory again as the collection.
- Below 500 elements the chain always runs as written.
- A change of the structure goes back through the chain as written. That is a push, a splice, or a new array; an index replaced is one element's change.
- It is a graph of computeds: a read inside a
batchsees the write before it, as with anyderived.
Checked in development. In qatjs dev and in @qatjs/test, every delta result is compared with the
chain as written. A difference is QX-INCREMENTAL-MISMATCH in the overlay, with the stage and the
element, and the page shows the chain's result. A build has no check.
When it is not proved. The derived is left as written: the same behavior, no speedup.
qatjs check --suggest lists each such chain with the reason (for example "(r) => r.at < Date.now() reads the clock"). Asked for with { incremental: true }, it is also the warning
QX-INCREMENTAL-UNPROVED. In .tsx, write derived(() => rows().filter(…)…, { incremental: true }).
watch with debounce or throttle
// search.qx
export default function Search() {
let query = state('')
let results = state<string[]>([])
// runs 300 ms after the typing stops; `throttle: 300` would run at most every 300 ms instead
watch(query, async (q) => (results = await api.search(q)), { debounce: 300 })
return <input bind:value={query} />
}query stateresults stateeffect takes no options: it re-runs whenever what it read changes. (In plain .ts, watch with
options comes from @qatjs/core/schedule; in .qx/.tsx the compiler picks it.)
Async errors
An error thrown by an event handler, or a rejected promise returned by an async one, goes to the
nearest onError handler (render(App, root, { onError }) or onError(fn)), then console.error
— never to an unhandled rejection. The same holds for async store actions (the caller can still
await and catch). Code that catches an error itself can pass it on with report(error) from
@qatjs/core.
Streams
A WebSocket or an EventSource is a pattern, not an API: write each message into state, and close
the connection when the component goes away.
// ticker.qx
export default function Ticker({ url }) {
let price = state<number | null>(null)
mount(() => {
const source = new EventSource(url)
source.onmessage = (e) => (price = JSON.parse(e.data).price)
return () => source.close() // runs on unmount
})
return <p>{price ?? '…'}</p>
}price state// chat.qx
export default function Chat() {
let messages = state<string[]>([])
mount(() => {
const ws = new WebSocket('wss://chat.example/room')
ws.onmessage = (e) => messages.push(e.data)
return () => ws.close()
})
return <ul>{for (const m of messages)}<li>{m}</li>{/for}</ul>
}messages stateFor a stream shared by many components, keep the signal in a module and open the connection once.