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 hooksthis.$state and this.$({ ... }) replace useState, useEffect, useMemo.No framework lifecycle hooksFirst-run guards, explicit owners, or native connectedCallback.No fragmentsReturn an array from $, or use plain functions for no wrapper.No portalsElements are real: append them wherever they belong.No memoizationMemoize the function, not the component, and only after measuring.No contextProps, a module-level variable, or an event bus.No useRef / createRefthis is the element and child refs live on this._ properties.No synthetic eventsHandlers get native DOM eventsNo built-in reactivityUpdates are explicit $() and render() calls.No SSR hydration contractThe reconciler reuses whatever matching DOM is already there.

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.x to read, this.$({ x: newValue }) to update and re-render.
  • useEffect: Code that runs directly in $(). Before replacing a timer in $, clearInterval / clearTimeout the old one. That only handles re-renders, not removal: for attach/detach cleanup, see Lifecycle. For first-run setup, use an explicit if (!this._initialized) guard and set the flag inside it. First render is not a mount hook.
  • useMemo: Compute values in $() directly, or cache on this._ keyed on the input (below).
  • useRef: this is the element. For refs to children, query with this.querySelector or stash in this._child.
  • useContext: A plain module-level variable, an event bus, or props passed down.
JSFragment
// 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 / window listeners, event-bus subscriptions), lift ownership, observe removal, or register the tag with customElements.define() and use disconnectedCallback. 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.
Persistent children

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.

JS
// 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:

JS
// 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:

JS
// 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.

Measure first

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.

JS
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:

JS
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.

Why this beats component-level caching
  • Shared across instances: ten my-list components 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._rendered or invalidation logic sprinkled through $().
  • Survives anything: the cache is a property on the function, so it lives as long as the function does.
Caveats worth knowing
  • 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'] returns Object.prototype.toString (truthy), so ??= never fires. If inputs are user-supplied strings, use Object.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.lookup or switch to a WeakMap keyed 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._:

JSFragment
$({ 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:

  1. Prop drillingPass values down explicitly. Usually fine up to 2-3 levels.
  2. Module-level variableDeclare let locale = 'en' at module scope and reference it from any component that needs it.
  3. Event busPub/sub for decoupled cross-component communication. See Architecture.
JS
// 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:

JS
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];
    }
});
Why this works

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 render explicitly

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.

JS
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.

Want signals anyway?

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.

What the server HTML needs
  • 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 example hidden: null.
HTMLFragment
<!-- 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#

React, Vue and Svelte features and their mx equivalents
FeaturemxReact / Vue / Svelte
State$state + this.$({...})useState
EffectsCode in $(), with an if (!this._initialized) first-run guard that sets the flag inside ituseEffect
MemoizationMemoized functions, or caching on this._ propertiesuseMemo / React.memo
Element refsthis is the element, with child refs via this.querySelector or this._childuseRef
Shared valuesProps, a module-level variable or an event bususeContext / Provider
FragmentsReturn an array from $, or plain functions for no wrapper<>...</>
Portalsdom() + document.body.appendcreatePortal
Imperative handlesMethods on the definition object (Object.assign mixin)Refs / forwardRef
Mount / unmountFirst-run guard, or connectedCallback / disconnectedCallback on a registered custom element (Lifecycle)onMount / onDestroy
ReactivityExplicit $() calls, or the updateAll() pattern for shared stateSignals / reactive refs
SSR hydrationAutomatic: the reconciler reuses matching DOMHydration markers + contract
EventsNative DOM eventsSynthetic events
TemplatesPlain function calls: mx.div(...)JSX / SFC templates
The philosophy

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."