Skip to content

Lifecycle hooks

What are lifeycle hooks

Lifecycle hooks are key moments in the life of a component. This framework exposes some basics hooks which can be extended with decorators.

HookTiming
mountedExecuted when the component is mounted by a parent or via the instance $mount method.
destroyedExecuted when the component is destroyed by a parent or via the instance $destroy method.
updatedExecuted when the component is updated by a parent or via the instance $update method.
terminatedExecuted when the instance $terminate method is called.

The lifecycle hooks diagram below present in greater detail how theses hooks works with one another.

Using lifecycle hooks

To use a lifecycle hook, declare it as a method of your class, the method will be executed by the internals of the framework at the right time.

js
import { Base } from '@studiometa/js-toolkit';

export default class Component extends Base {
  static config = {
    name: 'Component',
    log: true,
  };

  mounted() {
    this.$log('mounted');
  }

  updated() {
    this.$log('updated');
  }

  destroyed() {
    this.$log('destroyed');
  }

  terminated() {
    this.$log('terminated');
  }
}

TIP

Find details for the lifecycle hooks APIs in the Lifecycle hooks section in the API Reference.

When extending an existing component, do not forget to call the parent component hook methods via the super keyword:

js
import Parent from './Parent.js';

export default class Child extends Parent {
  static config = {
    name: 'Child',
  };

  mounted() {
    super.mounted(); // call the parent method
  }
}

Lifecycle hooks diagram

MIT Licensed