Skip to content

Lifecycle hooks

ts
mounted(): MountedReturn
unmounted(): void
ts
type 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.

js
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():

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

js
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

CauseCalls
the element enters the documentmounted()
a mount strategy's condition becomes truemounted()
the element leaves the documentunmounted()
the component token leaves data-componentunmounted(), then the instance is dropped
a breakpoint withdraws the declarationunmounted(), then the instance is dropped
a reversible strategy's condition endsunmounted()
the node is movedunmounted() 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, use option<Name>Changed(). For an attribute the framework does not read, use watchAttributes().
  • 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 own mounted() without super.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.

MIT Licensed