Core
Lifecycle without hooks
Most components need no lifecycle at all. mx has no onMount/onDestroy or componentDidMount, because a component builds its own structure when it's created, and a mount or destroy hook usually patches over unclear ownership of a resource. For the vast majority of components, state flows through $(), the reconciler patches the DOM, and nothing more is needed.
Ask who owns it#
A few components own something with a start and a stop tied to being on the page, such as a timer, a subscription, a ResizeObserver or a global listener. The instinct is to ask "which lifecycle hook?" - but the better question is who owns the resource, and how long does it live? Get that right and the lifecycle problem usually disappears. This is the order to try things in:
- Own lessLift the resource to a long-lived owner
- Self-pollA timer checks isConnected and clears itself
- ObserveA Mutation
Observer reports the removal - Be tolddisconnected
Callback, only if already a custom element
You almost never need to reach for Web Components / connectedCallback to clean up after a component. There is no component that strictly requires it - everything below has a registration-free answer. disconnectedCallback is the cleanest tool for one specific case, not a requirement. mx is fully compatible with custom elements if you want them (that's its own page), but cleanup is not the reason to adopt them.
First choice: move the resource to a longer-lived owner#
The cleanest teardown is the one you never write. If a resource can live on a long-lived owner - the app shell, a parent that outlives its children - put it there, and let the leaf components be stateless render-from-props functions. A live clock is the textbook case:
- App shellOwns setInterval and visibilitychange
- tick()Pushes the time with c.$({ time })
- <a-clock>Renders from props, owns nothing
// Leaf: pure render-from-props. No timer, no listener, no lifecycle.
define('a-clock', { $({ time }) { return mx.time(time); } });
// One long-lived owner (the app shell) holds the timer AND the single
// visibility listener. It lives as long as the page, so it never needs
// teardown - and clocks can be added/removed freely with zero leak risk.
let tick = () => document.querySelectorAll('a-clock')
.forEach(c => c.$({ time: new Date().toLocaleTimeString() }));
let timer;
let sync = () => {
clearInterval(timer);
if (!document.hidden) { tick(); timer = setInterval(tick, 1000); } // pause/resync on tab switch
};
document.addEventListener('visibilitychange', sync);
sync();Now the leaf <a-clock> owns no timer, listener or lifecycle. The reconciler can create and drop clocks however it likes, and there is nothing to leak. The single setInterval and the single visibilitychange listener live on the app, which lives for the whole page, so they never need to be torn down. Lifting the resource up did more than centralize it, because the cleanup problem goes away entirely.
Pushing derived state from one owner into many stateless components is exactly the updateAll() pattern. For anything "live" - dashboards, tickers, clocks, feeds - reach for this first. A leaf that reacts to a shared source almost always wants to be stateless, with the source owned above it.
When the resource must live on the element#
Sometimes ownership really does belong to the component - a self-contained widget you drop in anywhere, with no owner to hand the resource to. Then you do need to release it when the element leaves. What you reach for depends on the resource:
A self-polling timer
Runs on its own schedule, so every tick can check isConnected and clear itself.
A passive subscription
Never ticks, so it needs a real signal that the element left: an observer or disconnectedCallback.
A self-polling timer: check isConnected
A setInterval/setTimeout/rAF already runs on its own schedule, so it can check whether it's still wanted and clear itself. It needs no registration, and it's robust across every removal path - render() replacing it, an ancestor being removed, anything - because isConnected reflects document-attachment regardless of how the element was detached. Open Result, then remove the clock and add it back:
define('a-clock', {
$() {
// The interval checks isConnected each tick and clears ITSELF once
// the element leaves the document - by ANY removal path. No registration.
this._t ||= setInterval(() => {
if (!this.isConnected) { clearInterval(this._t); this._t = null; return; }
this.render(mx.time(new Date().toLocaleTimeString()));
}, 1000);
return mx.time('...');
}
});Construct and append before the first tick. After remounting the same instance, call clock.$({}) to rearm the cleared timer. This recipe does not detect attachment by itself.
It cleans up lazily - one extra tick after removal - and it only works for resources that poll. A passive subscription has no tick on which to check isConnected, so this technique does nothing for it.
A passive subscription: a removal hook
Passive resources such as bus.on(...), an addEventListener on document/window or a ResizeObserver wait for an external event and never poll. After the element is removed they keep firing against dead DOM and hold the element alive. They need an actual signal that the element left, and there are two ways to get one: an observer without registration, or native custom-element callbacks.
A self-disconnecting MutationObserver
Watch a stable ancestor. When you notice you've been detached, clean up and disconnect the observer so it doesn't leak either.
connectedCallback / disconnectedCallback
If the component is (or can be) a registered custom element, the platform hands you the exact callbacks. It fires on every removal path.
define('price-ticker', {
$() {
if (!this._init) {
this._init = true;
this._off = bus.on('price', p => this.render(mx.span('$' + p))); // passive subscription
// A removal hook with no custom element: watch a stable ancestor,
// clean up the moment we're detached, then disconnect ourselves.
this._mo = new MutationObserver(() => {
if (!this.isConnected) { this._off(); this._mo.disconnect(); }
});
this._mo.observe(document.body, { childList: true, subtree: true });
}
return mx.span('...');
}
});class PriceTicker extends HTMLElement {
connectedCallback() { this._off = bus.on('price', p => this.render(mx.span('$' + p))); }
disconnectedCallback() { this._off(); } // fires on every removal path, synchronously
}
customElements.define('price-ticker', PriceTicker);| Aspect | Option A: MutationObserver | Option B: disconnectedCallback |
|---|---|---|
| Registration | None - a plain define() component | customElements.define() |
| Timing | Microtask-async | Synchronous, per element |
| Cost | Every DOM mutation under document.body wakes it - real overhead if many components do it | Zero until removal, less code |
| Reuse | Disposable: append immediately, construct a fresh instance after cleanup rather than reconnecting the old subscription | Reconnects: connectedCallback subscribes again |
Either way, the bus must provide an unsubscribe function. Option B is the cleanest, because it runs synchronously per element, has zero overhead until removal and needs less code.
Option B is lighter and sharper than Option A, but it is not necessary - Option A covers the same ground without a custom element. Choose disconnectedCallback when the component is already a registered custom element (see Web Components for rendering mx inside one), not as a reason to register one. If you're writing a plain define() component and just need cleanup, the MutationObserver - or better, lifting the resource up - keeps you out of custom-element land entirely.
Two things that look like cleanup but leak#
Both of these seem to give a component control over its own teardown. Neither survives the reconciler.
Most of what destroy hooks were once used for, like nulling out variables by hand, the garbage collector already handles. What's left is timers, observers and global listeners, and those are safest on an owner that outlives the component.
Overriding remove()
Since define() does Object.assign(element, definition), you can shadow Element.prototype.remove with your own:
define('bad-clock', {
remove() { Element.prototype.remove.call(this); clearInterval(this._t); },
$() { this._t ||= setInterval(() => this.render(mx.time('' + Date.now())), 20); return mx.time('...'); }
});It fires when something calls the element's own .remove() - an explicit manual call. The reconciler uses removeChild for trailing cleanup and replaceWith (a position-matched child whose tag changed), which never touches your override - and ancestor removal detaches the whole subtree without calling any child's remove(). Measured:
| remove() override, removal path | Interval ticks (at removal -> later) | Result |
|---|---|---|
| Manual .remove() | 3 -> 3 | Stopped (override fired) |
| Reconciler replaceWith | 3 -> 9 | Leak |
| Ancestor removed | 7 -> 19 | Leak |
Mistaking imperative control for a lifecycle
Exposing $startClock/$stopClock methods (the methods-mixin) gives you control over a resource - but no signal for when the element is removed. So a passive listener registered in $ has nobody to remove it:
define('bad-clock', {
$startClock() { this._t ||= setInterval(() => this.render(mx.time('...')), 1000); return this; },
$stopClock() { clearInterval(this._t); this._t = null; return this; },
$() {
// A passive document listener with nobody to remove it. When the element
// is reconciled away, this listener stays on document forever - and on the
// next tab switch it RESTARTS the interval on a detached element.
document.addEventListener('visibilitychange', this._onVis ||= () =>
this[document.hidden ? '$stopClock' : '$startClock']());
return mx.time('...');
}
});When the parent reconciles this away, $ never runs again and nothing removes the visibilitychange listener, so it stays on document permanently and keeps the element alive. A running interval keeps rendering into the detached element, and every time the tab comes back into view the listener starts it again. The methods let you stop the clock, but they don't tell the component it's gone.
Both anti-patterns assume removal happens through a path you control. In a reconciler-driven UI it usually doesn't - a parent re-renders and the child vanishes via replaceWith or an ancestor swap, with no hook for you to hang teardown on. That's why the working answers are: lift the resource up (no removal to detect), poll isConnected (the element notices itself), a MutationObserver (the DOM tells you), or disconnectedCallback (the browser tells you).
Mount hooks have a similar trap. Their usual job is reading layout once the element is attached, but an attached element inside an inactive tab still reads a height of 0. Size from the parent container instead, which works because you hold the real element, or observe when it becomes visible.
Persistent children and explicit ownership#
A retained dom() container keeps third-party children outside MX reconciliation. The owner must initialize after attachment and destroy the instance on teardown. This integration assumes setupEditor provides setValue and destroy:
- appendAttach the element
- mount()Owner creates the editor
- $({ value })setValue on the live editor
- dispose()Owner destroys it
- remove()Detach, then remount the same way
// Integration: setupEditor(container, value) returns { setValue, destroy }.
// The owner calls mount() after attachment and dispose() before removal.
define('code-editor', {
$({ value = '' }) {
this._container ||= dom.div();
this._editor?.setValue(value);
return [this._container]; // MX preserves the external editor subtree
},
mount() {
if (!this.isConnected) throw new Error('Append editor before mount()');
this._editor ||= setupEditor(this._container, this.$state.value ?? '');
},
dispose() {
this._editor?.destroy();
this._editor = null;
}
});
let editor = dom.codeEditor({ value: 'hello' });
document.body.append(editor);
editor.mount();
// Owner teardown: editor.dispose(); editor.remove();
// Remount: document.body.append(editor); editor.mount();Returning the same container on each render preserves its children. If removal is outside the owner's control, use the removal strategies above and destroy the third-party instance there.
What you do not have to clean up#
Cleanup discipline matters, but don't over-rotate - the browser reclaims plenty for free:
Reclaimed with the element
- Handlers on the element -
onclickin a render description, orthis.onscroll. Removed with the element, and mx also nullifies stale render-assigned handlers via its attribute cache. - Child DOM - everything
render()built under the element goes away when the element does. - Closures over render-local state - collected once nothing references them.
What isn't reclaimed: the teardown checklist
setInterval/setTimeout- fire until cleared.- Observers - deliver until
disconnect(). - Listeners on
document/window/other nodes - outlive the element. - Event-bus / store / socket subscriptions - hold the element alive until unsubscribed.
- Third-party instances (charts, editors, maps) - leak their internals until you call their
destroy().
Choosing an approach#
| Situation | Reach for | Web Components? |
|---|---|---|
| Renders from props | define(), no lifecycle | No |
| A "live" leaf (clock, ticker, feed) | Lift timer/listener to a long-lived owner so the leaf stays stateless | No |
| Bare self-polling timer on the element | isConnected check inside the tick | No |
| Passive subscription on the element | Self-disconnecting MutationObserver... | No |
| ...or, if already a custom element | connectedCallback/disconnectedCallback (cleanest) | Yes (optional) |
| Third-party child (editor, chart) | Retained container whose owner calls mount() / dispose() | No |
In short
- There is no cleanup problem in mx that forces you into Web Components.
- Try things in this order: own less, then let the element notice its own removal (
isConnected/MutationObserver). - Reach for
disconnectedCallbackonly when the component is already a registered custom element - where it is the nicest tool. - mx is built to work inside custom elements when you want them, but cleanup just isn't the reason to.