Core
State without a store
Every component keeps a persistent $state object, siblings talk over a dozen-line event bus, and anything else is a container you re-render. Four plain patterns cover real apps, and none of them needs a library.
Four patterns built on the same idea#
Pick the smallest one that fits. Each card links to the full treatment below or elsewhere in the docs.
Local state
Keep state in the component instance. this.$() merges and re-renders.
define('a-toggle', {
$({ on = false }) {
let flip = () =>
this.$({ on: !on });
return mx.button(
{ onclick: flip },
on ? 'On' : 'Off');
}
});Event bus
Decouple siblings: a Map of channels, each a Set of listeners.
let off = bus.on('cart:add', item =>
badge.$({ item }));
bus.send('cart:add', item);
off(); // listener goes awayRe-render container
Update a subtree on demand from a plain variable.
let items = [];
let paint = () => list.render(
...items.map(item => mx.li(item)));
items.push('Buy milk');
paint(); // after every changeKeyed list with dom() + Map
Stable DOM nodes per key, moved by identity instead of rebuilt.
let rows = new Map(data.map(d =>
[d.id, dom.aRow({ data: d })]));
// Reorder: same nodes, moved by identity
table.render(...sorted.map(d =>
rows.get(d.id)));The path every update takes
Whichever pattern owns the data, an update always travels the same short path. There is no scheduler and no dependency graph between the event and the DOM.
- Eventclick, fetch, bus message
- Update statemutate or replace data
- .$() / render()merge and re-run
- Reconcilereal DOM patched in place
How $state works#
Every component has a this.$state object that persists across renders. When this.$({ ... }) is called, the argument is shallow-merged into $state via Object.assign, then the $ function runs with the merged state.
// What happens inside the framework (simplified):
interfaceObject.$ = function(state) {
let out = $.call(this, Object.assign(this.$state ||= {}, state));
// A single mx description is passed whole; an array of children is SPREAD.
out?._ ? this.render(out) : this.render(...out || []);
};This means every property you pass to this.$() is merged into the existing state. Properties you don't pass are left untouched.
Only top-level keys are merged. Nested objects and arrays are replaced, not recursively merged. If you pass this.$({ items: newArray }), the old array is gone.
Reading and updating state#
In practice, almost every component uses the same minimal pattern: destructure props with defaults, call this.$({...}) to update. $state accumulates behind the scenes and you rarely reference it directly.
define('a-counter', {
$({ count = 0, step = 1 }) {
let { div, button, span } = mx;
// count is destructured from $state after the merge.
// Default (= 0) applies on first render; later renders reflect
// whatever the parent or the component last set via $().
return div(
button({ onclick: () => this.$({ count: count - step }) }, '−'),
span(count),
button({ onclick: () => this.$({ count: count + step }) }, '+')
);
}
});
document.body.render(mx.aCounter({ count: 10, step: 5 }));Walkthrough
- First render: parent calls
el.$({ count: 10 }). The wrapper merges into$state, then calls your$with the merged object. Destructure givescount = 10. - User clicks +:
this.$({ count: 15 })merges into$stateand re-renders. Destructure givescount = 15. - Parent re-renders without passing count: merge is a no-op for that key. Destructure sees whatever value the component last committed.
- Parent re-renders passing count: 10: merge overwrites. Local value is replaced by the parent's value, which is usually what a parent wants.
The wrapper does Object.assign(this.$state, props) before your $ runs. If a parent re-renders and re-passes { count: 10 }, locally updated $state.count is overwritten to 10. ??= can't help because $state.count is already non-nullish by then.
If you want state that survives parent re-passes, use a different key: take the prop as a seed and keep local state separately.
define('counter', {
$({ initial = 0 }) {
// 'initial' is the seed; this._count is the local state
this._count ??= initial;
return [
mx.button({ onclick: () => { this._count--; this.$({}); } }, '−'),
mx.span(this._count),
mx.button({ onclick: () => { this._count++; this.$({}); } }, '+')
];
}
});This pattern needs this.$({}) to trigger a re-render, which is normally a code smell. The better fix is to have the parent own the state and pass it down, since truly local state that survives parent overrides is surprisingly rare in practice.
Generating persistent IDs#
Components like checkboxes and switches need a unique id to link <label> and <input>. Generate it once and store it in $state:
let counter = 0;
define('a-checkbox', {
$({ label, checked, onchange }) {
let { div, input, label: lbl } = mx;
// Generate ID once, reuse on every re-render
let id = (this.$state.id ??= 'chk-' + counter++);
return div(
input({ type: 'checkbox', id, '.checked': checked,
onchange(e) { onchange?.(e.target.checked); }
}),
lbl({ for: id }, label)
);
}
});The ??= assigns only when $state.id is nullish, so the id is generated once on the first render and reused unchanged on every later one.
Clearing and resetting state#
Because state auto-merges, a key you leave out keeps its old value, so clearing means you explicitly pass the reset value. Passing undefined leaves the key in $state, but destructuring defaults (= 0) and ??= both treat it as missing, so it resets to the default. Passing the empty value says what you mean more plainly.
define('tag-list', {
$({ items }) {
let selected = (this.$state.selected ??= new Set);
return [
mx.div(
...items.map(item =>
mx.button({
'aria-pressed': selected.has(item) ? 'true' : 'false',
onclick: _ => {
selected[selected.has(item) ? 'delete' : 'add'](item);
this.$({ items }); // re-render, selected persists
}
}, item)
)
),
selected.size ? mx.p('Selected: ' + [...selected].join(', ')) : null,
selected.size
? mx.button({ onclick: _ => {
// Pass a NEW Set to replace the old one
this.$({ items, selected: new Set });
// Clear all just removed itself: hand focus to the first tag
this.querySelector('button').focus();
}}, 'Clear all')
: null
];
}
});
document.body.render(
mx.tagList({ items: ['bug', 'feature', 'docs', 'urgent'] })
);- Mutating (
selected.add(item)) works because the Set is the same object in$state. It persists automatically. - Replacing (
this.$({ selected: new Set })) is the simplest way to clear or reset. The merge replaces the old Set with a new empty one.
Reading state in callbacks#
Event handlers in the returned description are rebuilt on every render, so they always see the current props. A callback that outlives the render, such as a timer, a listener on document or a third-party library's hook, still holds the variables of the render that created it. When it needs the latest state, read this.$state instead:
define('auto-save', {
$({ text }) {
// The interval is created once and outlives this render. Destructured
// props would stay those of the first render, so read this.$state:
// the wrapper merges the latest props into it before every $ call.
this._t ||= setInterval(_ => {
if (!this.isConnected) return clearInterval(this._t);
this.$state.onSave?.(this.$state.text);
}, 5000);
return mx.span(text);
}
});Destructured props ($({ onSave })) are fixed for the render that created them. A handler inside the returned description is replaced on the next render, so it always sees current values. A callback captured once keeps the first render's values. The wrapper merges new props into $state before every $ call, so this.$state always has the latest ones.
Cross-component coordination (the event bus)#
$state handles state within a component, and props pass state down to children. But siblings that don't share a parent (a cart button and a header badge, a filter pill and a results table) need a sideways channel. A pub/sub bus of about a dozen lines does that job without a store library:
// The whole primitive: a Map of channel name -> Set of listeners.
// A few hundred bytes of source. No dependency, no build step.
let bus = (() => {
let channels = new Map;
return {
on(name, fn) {
let set = channels.get(name) ?? channels.set(name, new Set).get(name);
set.add(fn);
return () => set.delete(fn); // returns its own unsubscribe
},
send(name, data) {
channels.get(name)?.forEach(fn => fn(data));
}
};
})();The whole bus is a Map of channel name to a Set of listeners. send fires them, while on registers one and hands back a function that removes it. The important detail is that subscribing returns the unsubscribe function, which makes cleanup a single line wherever you listen.
Producers and consumers
Anything can send and anything can listen. Components that mount and unmount subscribe on attach and unsubscribe on detach, so they never leak or fire against dead DOM:
// Producer: anything can send - a click, a fetch callback, a socket message
mx.button({ onclick: () => bus.send('cart:add', item) }, 'Add to cart')
// Consumer A - plain app-level wiring, no component required:
let badge = dom.span('0');
let count = 0;
bus.on('cart:add', () => badge.textContent = ++count);
// Consumer B - a component that comes and goes. Subscribe on attach,
// unsubscribe on detach, so a removed component stops listening.
class CartBadge extends HTMLElement {
connectedCallback() { this._off = bus.on('cart:add', d => this.bump(d)); }
disconnectedCallback() { this._off(); } // exactly the cleanup .on() handed back
bump() { /* update the view */ }
}
customElements.define('cart-badge', CartBadge);The component half of that pairing is the subscription lifecycle. Consumer B is already a custom element, so it subscribes in connectedCallback and calls the returned unsubscribe in disconnectedCallback. For a plain define() component, lift the subscription to a long-lived owner or use the self-disconnecting MutationObserver described there. For app-level wiring that lives as long as the page, you can just on() and never unsubscribe.
Live: one channel, two listeners
The button below knows nothing about what reacts to it. Two independent views both subscribed to the like channel, and the producer just sends:
let bus = (() => {
let channels = new Map;
return {
on(name, fn) {
let set = channels.get(name) ?? channels.set(name, new Set).get(name);
set.add(fn);
return () => set.delete(fn);
},
send(name, data) { channels.get(name)?.forEach(fn => fn(data)); }
};
})();
let likes = 0;
let count = dom.strong('0 likes');
let log = dom.div();
// Two independent views, both listening to one channel - neither knows
// about the other, or about the button that fires the event
bus.on('like', () => count.textContent = ++likes + (likes === 1 ? ' like' : ' likes'));
bus.on('like', () => log.prepend(dom.div('❤ someone liked this')));
let host = dom.div();
host.render(
dom.button({ onclick: () => bus.send('like') }, 'Like'),
count,
log
);
document.body.render(host);Funnelling into one update
In a dashboard where many components share one source of truth, don't let each component react to the bus independently. Funnel events into a single updateAll() that pushes derived state to everyone in one pass. That pattern, and the production event table behind it, are on the Architecture page.
Across tabs, only when you need it
The bus above is in memory, so it's synchronous and never serializes or copies anything. In-tab eventing should stay that cheap. BroadcastChannel is for cross-tab messaging, and using it for in-tab coordination is heavy-handed. When you do need other tabs to react (logout everywhere, sync a cart across windows), bolt it on as a thin forwarder rather than replacing the bus:
// In-tab eventing should stay in-tab: the bus above is synchronous and
// serialization-free. Add BroadcastChannel ONLY when other tabs must hear
// it too - as a thin forwarder on top, not the default path.
let tabs = new BroadcastChannel('app');
tabs.onmessage = e => bus.send(e.data.name, e.data.data); // remote -> local bus
function sendEverywhere(name, data) {
bus.send(name, data); // local listeners, synchronous, no copy
tabs.postMessage({ name, data }); // other tabs (data must be structured-cloneable)
}
// sendEverywhere('auth:logout') -> every open tab logs outThe bus is a few hundred bytes of source, just a Map of Sets and two methods. The equivalent state primitive a compiled framework ships is several times larger, and it's a fixed cost in every bundle whether the app coordinates anything or not. Here it's code you paste once and own, and you can read all of it.
Signal-lite reactivity (sample pattern)#
mx has no built-in state management, because most state belongs to a boundary such as a side panel, a large table or a dialog, which owns its data and re-renders itself. When a dialog is dismissed its state goes with it, instead of lingering in a global store for the life of the page. A shared store only earns its place for truly global data you fetch once, like user preferences or feature flags. Re-rendering a container from a plain variable covers most cases. But if you want a pub/sub primitive, here's a sample implementation in about a dozen lines. This is not part of mx but it's just a pattern you can copy and adapt.
The idea is a getter function with .set() and .subscribe() methods. The bind() helper wires a signal to a DOM container so it re-renders automatically on every change.
// about a dozen lines
let signal = (v) => {
let subs = new Set();
let get = () => v;
get.subscribe = (fn) => (subs.add(fn), () => subs.delete(fn));
get.set = (nv) => { v = nv; subs.forEach(fn => fn(nv)); };
return get;
};
let bind = (place, view, sig) => {
place.render(view(sig()));
return sig.subscribe(v => place.render(view(v)));
};| Call | Does |
|---|---|
| signal(initialValue) | Returns a getter function. Call it to read the value. |
| .set(newValue) | Updates the value and notifies all subscribers. |
| .subscribe(fn) | Registers a listener and returns an unsubscribe function. |
| bind(el, viewFn, signal) | Renders viewFn(value) into el and auto-updates on changes. |
Counter demo using signals
Create a signal, bind it to a host element, and update it from event handlers:
// Usage
let count = signal(0);
let host = dom.div();
bind(host, v => mx.div(
mx.button({ onclick(){ count.set(v - 1) } }, "−"),
mx.span(v),
mx.button({ onclick(){ count.set(v + 1) } }, "+")
), count);
document.body.render(host);This is not part of mx but it's a sample implementation. For most apps, re-rendering a container from a plain variable is simpler and sufficient. Copy this if you find it useful, and modify or replace it as you see fit.