@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_componentsmobx 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
- Instantiates the wrapped component
- Analyzes it for which meta-components it uses
- Creates the appropriate "Managers" for each meta-component
- Triggers each manager's
process_hooksmethod
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
accessorkeyword on Stage-3 decorated fields. Plainfielddecoration 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
/mobxsubpath requiresmobx >= 6.11to 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.
