Lifecycle hooks
mounted(): MountedReturn
unmounted(): voidtype MountedReturn = void | (() => void) | MountedReturn[] | Promise<MountedReturn>;Both are meant to be overridden and neither needs a super call.
mounted()
Runs when the element is in the document and the component's mount conditions are met. It runs after every option<Name>Changed() hook of the same cycle.
import { Base } from '@studiometa/js-toolkit';
class Player extends Base {
static config = { name: 'Player' };
mounted() {
this.$el.setAttribute('aria-live', 'polite');
}
}It returns its cleanup
A function, an array of functions, sync or async. They run on the next $unmount():
import { Base, useScroll } from '@studiometa/js-toolkit';
class Header extends Base {
static config = { name: 'Header' };
mounted() {
return useScroll().subscribe(({ directionY }) => {
this.$el.classList.toggle('is-hidden', directionY > 0);
});
}
}If an async mounted() resolves after the unmount, the cleanup runs immediately.
unmounted()
Runs at the end of $unmount(), after the cycle's listeners are unbound, the mounted() cleanups have run and the scheduled tasks are cancelled.
import { Base } from '@studiometa/js-toolkit';
class Player extends Base {
static config = { name: 'Player' };
unmounted() {
this.$el.removeAttribute('aria-live');
}
}It stays available for the cases the returned cleanup does not fit. When both exist, the returned cleanup runs first.
What triggers each
| Cause | Calls |
|---|---|
| the element enters the document | mounted() |
| a mount strategy's condition becomes true | mounted() |
| the element leaves the document | unmounted() |
the component token leaves data-component | unmounted(), then the instance is dropped |
| a breakpoint withdraws the declaration | unmounted(), then the instance is dropped |
| a reversible strategy's condition ends | unmounted() |
| the node is moved | unmounted() then mounted(), same identity |
Unmounting a parent does not unmount its children.
What is not a lifecycle hook
updated()does not exist. For an option that chooses a resource, useoption<Name>Changed(). For an attribute the framework does not read, usewatchAttributes().- There is no permanent state. A component never declares that its work is over. "Once per element" is a plain field — see Lifecycle.
- A service mixin never occupies either hook. It overrides
$mount()/$unmount(), so a class that writes its ownmounted()withoutsuper.mounted()still subscribes.
Failures
A hook that throws is reported once as component.lifecycle-failed and the cycle continues. It does not stop the other instances in the same batch.