Reference
What mx is not
mx is a reconciler rather than a framework, and it deliberately leaves out a lot of what React, Vue and Svelte provide, so it doesn't decide your tooling or architecture for you. If you're coming from one of those, here is what's missing and what you use instead.
The short version#
mx has render, state and components. Everything else is plain JavaScript. Each row below is a feature you may be looking for, and what you write instead.
Frameworks tend to bring their tooling along: React's own docs point you to a framework such as Next.js, and Svelte doesn't exist without its compiler. mx is one piece of the puzzle, closer to jQuery, which smoothed over browser differences and never told you how to build your app. You choose concatenation or ES modules and your own architecture, and because mx hydrates whatever HTML is already there, it works on a WordPress or Drupal page as well as in a real-time dashboard.
No hooks#
There's no useState, useEffect, useMemo, useRef or useContext, and no rules-of-hooks, so a plain if or an early return is always allowed and you never debug call order or one hook affecting another. Each one maps to something you already know:
useState:this.$state.xto read,this.$({ x: newValue })to update and re-render.useEffect: Code that runs directly in$(). Before replacing a timer in$,clearInterval/clearTimeoutthe old one. That only handles re-renders, not removal: for attach/detach cleanup, see Lifecycle. For first-run setup, use an explicitif (!this._initialized)guard and set the flag inside it. First render is not a mount hook.useMemo: Compute values in$()directly, or cache onthis._keyed on the input (below).useRef:thisis the element. For refs to children, query withthis.querySelectoror stash inthis._child.useContext: A plain module-level variable, an event bus, or props passed down.
// useMemo equivalent
$({ items }) {
if (this._itemsKey !== items) {
this._itemsKey = items;
this._sorted = [...items].sort((a, b) => a.name.localeCompare(b.name));
}
return mx.ul(...this._sorted.map(i => mx.li(i.name)));
}No framework lifecycle hooks#
A define()d component has no componentDidMount or onMount / onDestroy. The $ function is the only entry point, and it runs on render, not on attach or detach.
That's a property of define(), not a limit of the platform. Custom elements have connectedCallback and disconnectedCallback natively, and mx composes with them. When ownership requires platform attachment callbacks you can use them directly. Registration-free cleanup alternatives are documented too. The details are on the Lifecycle page.
The common cases
Most cases don't need a real lifecycle. Consider ownership and setup separately:
- First-run logic: use
if (!this._initialized) { this._initialized = true; /* setup */ }inside$. It runs the first time$is called, which suits one-time setup with no teardown. - Wait until in DOM: let the owner call an initialization method after appending. If polling is necessary, cancel it when the owner abandons the instance.
- Real attach/detach cleanup: for anything that must stop when the element is removed (timers, observers,
document/windowlisteners, event-bus subscriptions), lift ownership, observe removal, or register the tag withcustomElements.define()and usedisconnectedCallback. Element-local handlers and child DOM are reclaimed automatically, but those resources are not. See what you do and don't have to clean up.
See the persistent editor recipe for a retained container and explicit mount/dispose ownership. Do not return an empty child list after installing editor DOM.
No fragments#
There's no <>...</> or <Fragment>. A component returns either a single mx description or an array of children. Arrays are spread into the host element.
// Return multiple top-level children by returning an array
define('card-body', {
$({ title, body }) {
return [
mx.h3(title),
mx.p(body),
mx.hr()
];
}
});The component element itself (e.g. <card-body>) is the wrapper. If you don't want a wrapper tag, you can't have one: mx components are custom elements, so they occupy a real DOM slot. Plain functions don't have this constraint:
// Plain function - no wrapper element
let CardBody = ({ title, body }) => [
mx.h3(title),
mx.p(body),
mx.hr()
];
// Used with spread
mx.div(...CardBody({ title: 'Hi', body: 'Body' }))No portals#
There's no ReactDOM.createPortal. If you need to render into a different DOM location (modals, toasts, tooltips), render into it directly:
// Toast container, appended to body once
let toastContainer = null;
function toast(msg) {
if (!toastContainer) {
toastContainer = dom.div({ class: 'toast-container' });
document.body.append(toastContainer);
}
let t = dom.div({ class: 'toast' }, msg);
toastContainer.append(t);
setTimeout(() => t.remove(), 4000);
}There is no portal abstraction because none is needed. Elements are real, so you can append them anywhere.
No memoization#
There's no React.memo, PureComponent or $memo. Components re-render whenever their parent calls $() on them, and the reconciler keeps DOM updates minimal by diffing attributes against a per-element cache of what the last render set.
Before caching anything, measure the actual workload, including component computation and browser layout. Reconciliation benchmark results do not establish whether caching helps your application.
When a computation really is expensive
Memoize the function, not the component. The cache lives as a property on the function itself, so you don't need an external variable, a closure wrapper or a generic helper. Functions are objects and can hold properties like any other.
function expensiveFormat(arg) {
let c = expensiveFormat.lookup ||= Object.create(null);
return c[arg] ??= new Intl.NumberFormat('en-US').format(arg);
}
// Component stays trivial - no bookkeeping, no keys, no cache invalidation
define('my-list', {
$({ items = [] }) {
return mx.ul(...items.map(i => mx.li(expensiveFormat(i.id))));
}
});The ||= initializes the cache on the first call and ??= fills a slot only if it's nullish. The body is two lines, and it works for string and number inputs.
For object inputs (where you want reference-identity matching), use a Map. Plain objects stringify keys, so cache[item] becomes cache["[object Object]"] and every item collides:
function expensiveFormat(item) {
let c = expensiveFormat.lookup ||= new Map;
if (!c.has(item)) c.set(item, JSON.stringify(item));
return c.get(item);
}For object inputs where entries should be garbage-collected when the object is freed, use new WeakMap instead.
- Shared across instances: ten
my-listcomponents formatting the same item do the work once, not ten times. - Shared across call sites: the table, the tooltip and the summary panel all hit the same cache.
- No per-component bookkeeping: you don't need
this._key,this._renderedor invalidation logic sprinkled through$(). - Survives anything: the cache is a property on the function, so it lives as long as the function does.
- Pure inputs only: if the function depends on anything outside the arg (locale, user settings, time), include it in the key or bust the cache when it changes.
- Reserved keys on plain objects:
lookup['toString']returnsObject.prototype.toString(truthy), so??=never fires. If inputs are user-supplied strings, useObject.create(null)or a Map as the cache. - Unbounded growth: the cache never forgets. For long-lived apps with many unique inputs, periodically
delete expensiveFormat.lookupor switch to aWeakMapkeyed on object inputs.
When component-level caching is the right tool
If the expensive work is specific to one component instance (a per-instance sort order, a scroll-window computation, a layout measurement), cache on this._:
$({ items = [] }) {
// Cache the derived value per instance, keyed on the input reference
if (this._itemsRef !== items) {
this._itemsRef = items;
this._sorted = [...items].sort((a, b) => a.name.localeCompare(b.name));
}
return mx.ul(...this._sorted.map(i => mx.li(i.name)));
}Use function-level memoization for shared pure work and component-level caching for per-instance derived state, though most apps don't need either.
No context#
There's no Provider / Consumer or useContext, and in practice you rarely miss it. Data usually changes shape on its way down: a view loads it, a section prepares it, a tab looks up labels and a component draws it, so each level passes on something different rather than the same value. When a value really does need to travel further than two or three levels, that usually means it's being loaded or owned too high up, and the section or tab that uses it should own it instead. It also keeps debugging simple, because when a tab shows the wrong data you open that tab, look at what it received, and walk up one parent at a time until you find where it went wrong.
Most of what context gets used for is something the platform already does. A theme is the usual example, and it's a good illustration of what not to build, because it turns styling into component state. Set data-theme on body and let CSS custom properties cascade, and if one section should be light inside a dark app, give that section its own data-theme and everything underneath follows. No component re-renders at all.
Permissions and feature flags work the same way without a Provider. They're loaded once at login, the view that owns a screen reads them and passes each component whether it should show or allow something. For a value that changes app-wide, like switching dates between relative and absolute, format everything through one shared function and let the components that display it listen for the change on the event bus and re-render themselves.
For the few values that really are app-wide, here are three alternatives, in order of increasing decoupling:
- Prop drillingPass values down explicitly. Usually fine up to 2-3 levels.
- Module-level variableDeclare
let locale = 'en'at module scope and reference it from any component that needs it. - Event busPub/sub for decoupled cross-component communication. See Architecture.
// Module-level shared state - simplest option
let auth = { user: null };
define('nav-bar', {
$() {
return auth.user
? mx.span('Hi, ' + auth.user.name)
: mx.a({ href: '/login' }, 'Log in');
}
});No useRef / createRef#
this inside $ is the component element itself: that's your "ref". For references to child elements, store them in this._ properties:
define('auto-focus', {
$({ value, focused }) {
this._input ||= dom.input({
'.value': value,
oninput: e => this.$({ value: e.target.value })
});
if (!focused) {
this.$({ focused: true }); // recursive render appends the input to the DOM
this._input.focus(); // now it's mounted, focus works
}
return [this._input];
}
});Calling this.$({ focused: true }) inside $ triggers a recursive render. The inner call enters the "else" path (focused is now true), returns [this._input], and the reconciler appends the input to the component element. Control returns to the outer call, where this._input.focus() finds the input attached to the component.
One caveat: .focus() only moves focus if the host element is itself in the document. If you create the component with dom() and focus before appending the host, defer the focus (a requestAnimationFrame, or connectedCallback: see Lifecycle). When the host is already mounted, the synchronous call works as shown.
Updates should call this.$({ ... }). Direct $state writes change state but do not render. Controlled one-time default initialization inside $ is valid, but later updates must explicitly render.
There's no forwardRef, refs-as-callbacks or useImperativeHandle. If you need to expose methods, put them on the definition object (see Methods beyond $).
No synthetic events#
Event handlers are set as native DOM properties (element.onclick = fn). There's no synthetic event pooling or e.persist(). e is a real MouseEvent / KeyboardEvent / etc. and is safe to keep a reference to.
mx.button({
onclick: e => {
// e is a native MouseEvent - no pooling, no persist() needed
console.log(e.clientX, e.target, e.currentTarget);
setTimeout(() => console.log(e.target), 1000); // still valid
}
}, 'Click')Because these are the browser's own events, they fire in the order the DOM defines, and what you learn about them applies in any project. React adds its own event system on top, and Vue and Angular each have their own rules, so knowledge learned there doesn't carry over.
No built-in reactivity#
There are no signals, observables, ref(), computed() or implicit dependency tracking. State updates are explicit: you call this.$({...}), or you re-render a container by calling render() on it.
Explicit updates make dataflow visible. For views sharing state, the updateAll() pattern (Architecture page) avoids maintaining a dependency graph but may update more components. Compare it with signals on your own workload, because neither universally scales better.
A 20-line sample implementation is on the State page. It's not part of mx but it's a pattern you can copy.
No SSR hydration contract#
mx has no hydration markers (data-reactroot, $$scope, hk=). It doesn't need them, because the reconciler walks the existing DOM children in order and reuses each one whose tag matches the description at that position. Text and the attributes the description names are patched in place.
Call this parasitic hydration: mx attaches to whatever HTML is already on the page and takes over from there. You don't have a client/server contract to keep, framework-specific markup to emit at build time or mismatch errors to debug. If the server-rendered tree looks structurally like what render() is about to produce, mx reuses those nodes in place. If it doesn't, the reconciler replaces them and moves on. Server-rendered markup, hand-written HTML and static templates all work as hydration sources, as long as the HTML follows the two rules below.
- No whitespace between tags: whitespace is a text node and takes up a position, so formatted HTML shifts every element one step and none of them is reused. Ship it minified, as this site does.
- No attributes the description leaves out: mx only removes attributes it set itself, so one that only the server HTML carries (
hidden,disabled,aria-*) stays. Leave it out of the server HTML or name it in the description, for examplehidden: null.
<!-- Static HTML shipped by server, minified -->
<div id="app"><h1>Welcome</h1><p>Server-rendered content</p></div>
<script>
// Client picks up where server left off - no hydration marker needed
document.getElementById('app').render(
mx.h1('Welcome'), // matches existing h1, reused
mx.p('Client-updated content') // matches existing p, text updated
);
</script>See the SSG section for the build-time pattern. This docs site is built that way.
Summary table#
| Feature | mx | React / Vue / Svelte |
|---|---|---|
| State | $state + this.$({...}) | useState |
| Effects | Code in $(), with an if (!this._initialized) first-run guard that sets the flag inside it | useEffect |
| Memoization | Memoized functions, or caching on this._ properties | useMemo / React.memo |
| Element refs | this is the element, with child refs via this.querySelector or this._child | useRef |
| Shared values | Props, a module-level variable or an event bus | useContext / Provider |
| Fragments | Return an array from $, or plain functions for no wrapper | <>...</> |
| Portals | dom() + document.body.append | createPortal |
| Imperative handles | Methods on the definition object (Object.assign mixin) | Refs / forwardRef |
| Mount / unmount | First-run guard, or connectedCallback / disconnectedCallback on a registered custom element (Lifecycle) | onMount / onDestroy |
| Reactivity | Explicit $() calls, or the updateAll() pattern for shared state | Signals / reactive refs |
| SSR hydration | Automatic: the reconciler reuses matching DOM | Hydration markers + contract |
| Events | Native DOM events | Synthetic events |
| Templates | Plain function calls: mx.div(...) | JSX / SFC templates |
Every omission is deliberate. mx is under 1 KB brotli because it does one thing (reconcile a DOM tree) and trusts the language and platform for everything else. If you find yourself wanting a feature that's not here, the answer is almost always "plain JavaScript does that."