Skip to content

Using decorators

What are decorators?

Decorators are higher-order functions that wrap a Base class (or any class extending it) to add new behavior. Each decorator returns a new class with extra capabilities — lifecycle hooks, event listeners, observers — without modifying the original class.

How to use a decorator

Pass your base class to the decorator function, then extend the result:

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

class MyComponent extends withScrolledInView(Base) {
  static config = {
    name: 'MyComponent',
  };

  scrolledInView({ progress }) {
    console.log('Scroll progress:', progress.y);
  }
}

Combining decorators

Decorators can be chained by nesting them. The innermost decorator is applied first:

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

class MyComponent extends withScrolledInView(withMountWhenInView(Base)) {
  static config = {
    name: 'MyComponent',
  };

  scrolledInView({ progress }) {
    console.log('Scroll progress:', progress.y);
  }
}

You can also compose them step by step for readability:

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

const BaseWithInView = withMountWhenInView(Base);
const BaseWithScroll = withScrolledInView(BaseWithInView);

class MyComponent extends BaseWithScroll {
  static config = {
    name: 'MyComponent',
  };
}

When to use which decorator

NeedDecoratorDescription
Respond to viewport sizewithBreakpointObserverReact to active/inactive breakpoints
Manage breakpoint-dependent configwithBreakpointManagerSwitch full configs per breakpoint
Responsive optionswithResponsiveOptionsOptions that change value per breakpoint
Scroll-linked animationswithScrolledInViewProgress-based scroll callbacks
Mount only when visiblewithMountWhenInViewLazy mount on intersection
Mount on media querywithMountOnMediaQueryMount/destroy based on a media query
Mount when motion is allowedwithMountWhenPrefersMotionRespects prefers-reduced-motion
Drag interactionswithDragDrag handlers with inertia support
Relative pointer trackingwithRelativePointerPointer position relative to element bounds
Intersection observerwithIntersectionObserverRaw IntersectionObserver access
DOM mutationswithMutationMutationObserver integration
Group componentswithGroupCoordinate sibling component instances
Extra configwithExtraConfigOverride config on an existing class
Freeze optionswithFreezedOptionsPrevent option changes after mount

API Reference

Find all natively available decorators and their full API details in the Decorators section of the API Reference.

MIT Licensed