npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@matchlighter/meta_components

v0.6.13

Published

Meta Component's primary function is to add snippets of functionality to Class-Based components. It's basically React Hooks for class components.

Downloads

732

Readme

@matchlighter/meta_components

Meta Component's primary function is to add snippets of functionality to Class-Based components. It's basically React Hooks for class components.

I'm a child of the OOP Generation, so OOP tends to make more sense and looks cleaner to me. However, I really liked the idea and functionality behind hooks like useContext and I wanted similar features in Class-Based components without committing any massive, eye-paining sins (like nested Context Consumers to pass multiple Contexts to one Component).

This library is designed to be very extensible, allowing other libraries to write their own meta components.

Installation

npm install @matchlighter/meta_components

mobx is an optional peer dependency; only required if you import the @matchlighter/meta_components/mobx subpath.

The library uses TC39 Stage-3 decorators (preferred) and also supports the legacy/experimental decorator syntax. Configure your toolchain accordingly:

// babel.config.js
module.exports = {
  presets: ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"],
  plugins: [["@babel/plugin-proposal-decorators", { version: "2023-11" }]],
};
// tsconfig.json - Stage-3 decorators (TypeScript 5+)
{
  "compilerOptions": {
    "target": "ES2022",
    "useDefineForClassFields": false
  }
}

Stage-3 and Legacy decorators cannot be mixed within a single component class.

Design

A "Meta Component" is a custom construct that is initialized when a @with_meta_components-decorated Class Component is constructed. Most simply, meta-components are a set of React Hooks that are run next to, and then integrated with, a Class Component. This is achieved by wrapping the Class Component in a special functional component. The functional component

  1. Instantiates the wrapped component
  2. Analyzes it for which meta-components it uses
  3. Creates the appropriate "Managers" for each meta-component
  4. Triggers each manager's process_hooks method

Managers

Managers are intended to be Singleton for each type of meta-component.

For example, there's a built-in @hook meta-component. When used, the @hook decorator registers that the calling Component needs the HooksMetaManager Manager when the Component is constructed. It then registers details about the hook that the developer wants to be invoked. When the Component is constructed, the special wrapper function instantiates a HooksMetaManager and tells it to process_hooks. It then reads the data stored by @hook and invokes the hooks.

You could create a Manager Factory and register a separate Manager Class for each @ usage as well, but the one manager class per Meta Component type is preferred.

Usage

@with_meta_components

Class-level decorator that wraps a React.Component so that meta-components attached to it actually run.

import React from "react";
import { with_meta_components, context } from "@matchlighter/meta_components";

const ThemeContext = React.createContext<"light" | "dark">("light");

@with_meta_components
class MyComponent extends React.Component {
    @context(ThemeContext) accessor theme!: "light" | "dark";

    render() {
        return <div data-theme={this.theme}>Hello</div>;
    }
}

You may also apply it as a HOC (required for ref forwarding under class decorators):

class Inner extends React.Component { /* ... */ }
export default with_meta_components(Inner);

If you cannot apply it via class-decorator syntax (because of ref forwarding requirements), pass refs either through the _ref prop or wrap with the Reffable helper.

Built In Meta components

meta-components ships with some simple, built-in meta-components:

@hook

This meta-component is used as a property-decorator, like so:

@hook(() => useContext(SomeContext)) accessor value!: SomeContextType;

The value returned by the hook is set as the value of the decorated property.

Use the accessor keyword on Stage-3 decorated fields. Plain field decoration emits a runtime warning and may not update on re-render.

@context

Because the above pattern would be so common, a shortcut is provided that can be used like such:

@context(SomeContext) accessor value!: SomeContextType;

@mount_effect

This hook can decorate a class method. It will call the decorated method when the component is mounted.

@mount_effect
onMount() {
    console.log("mounted");
}

@hook_callback

This meta-component is similar to @hook, but instead of having its return value set as the value of a class-property, the decorated value/method is passed to the hook. @mount_effect uses this internally. As an example, here is how you could implement @mount_effect:

@hook_callback((f) => useEffect(f, []))
onEffect() {
    // Do Something on Mount
}

@hooks

Decorate a method to execute it once during the wrapping render — useful when you want to call several React hooks together without binding their results to specific fields.

@hooks
useFeature() {
    const value = useContext(MyContext);
    useEffect(() => { /* ... */ }, []);
    this.value = value;
}

@lifecycle

Decorate a class field whose value implements { [handle_lifecycle]: (event) => void }. The marked object receives 'mounted' and 'unmounted' events tied to the component's React useEffect mount cycle. Useful for plugging plain objects into mount/unmount without sprinkling componentDidMount/componentWillUnmount everywhere.

import { lifecycle, handle_lifecycle } from "@matchlighter/meta_components";

class Subscription {
    [handle_lifecycle](event: "mounted" | "unmounted") {
        if (event === "mounted") this.connect();
        if (event === "unmounted") this.disconnect();
    }
    connect() { /* ... */ }
    disconnect() { /* ... */ }
}

@with_meta_components
class MyComponent extends React.Component {
    @lifecycle accessor subscription = new Subscription();
    render() { return null; }
}

@store

Decorate a field holding a Store-shaped object ({ activate?(): void | (() => void); deactivate?(): void }). On mount, the store's activate() runs (its return value, if a function, is treated as the teardown). On unmount, deactivate() and any returned teardown run.

import { store, Store } from "@matchlighter/meta_components";

class CounterStore implements Store {
    interval: any;
    activate() {
        this.interval = setInterval(() => { /* ... */ }, 1000);
        return () => clearInterval(this.interval);
    }
}

@with_meta_components
class Widget extends React.Component {
    @store accessor counter = new CounterStore();
    render() { return null; }
}

@autorun

If you're using MobX for state management, there's also an @autorun meta-component. This meta-component will setup a MobX Autorun (from the decorated method) when the Component mounts and ensure that it is disposed when the Component unmounts. It may be used like so:

import { autorun } from "@matchlighter/meta_components/mobx";

@autorun({ /* MobX Autorun options*/ })
autorunningMethod() {
    // Read and do something with an Observable
}

Importing the /mobx subpath requires mobx >= 6.11 to be installed.

Extending

You can create your own meta-components either as simple functions or, for more complex behaviour, by writing a custom Manager.

Simple meta-components

A simple meta-component is just a function invoked during construction. It receives the owner (component instance) and the root manager. Use add_metacomponent to register it from inside your decorator.

import { add_metacomponent } from "@matchlighter/meta_components";

export function log_mount() {
    return (target: any, ctx: ClassFieldDecoratorContext) => {
        add_metacomponent(ctx, ({ owner }) => {
            useEffect(() => {
                console.log(`${owner.constructor.name} mounted`);
            }, []);
        });
    };
}

Custom Managers

For meta-components that share setup work or batch operations across many entries, extend AbstractManager:

import { AbstractManager, add_metacomponent } from "@matchlighter/meta_components";

class TimerMetaManager extends AbstractManager {
    process_entry_hooks(spec: { every: number; key: string }) { /* per-entry */ }

    process_pre_hooks() {
        // Called once before any entry hooks.
        // Safe place for `useState` / `useRef` shared across entries.
    }

    process_post_hooks() {
        // Called once after entry hooks. Useful for `useEffect` that depends on
        // the full set of entries.
        useEffect(() => {
            const ids = this.components.map(c =>
                setInterval(() => this.owner[c.key](), c.every)
            );
            return () => ids.forEach(clearInterval);
        }, []);
    }
}

export function interval(every: number) {
    return (target: any, ctx: ClassMethodDecoratorContext) => {
        add_metacomponent(ctx, TimerMetaManager, { every, key: ctx.name as string });
    };
}

For a real-world example of an external library leveraging meta-components, see @matchlighter/fetcher.