useReactiveInstance
This version is deprecated
This documentation is for use-less-react v0.x, which has been deprecated.
See v1.0 documentation for the current API.
React hook that binds a reactive class (extending PubSub or PubSubMixin) to a React component.
Overview
useReactiveInstance allows your UI to automatically update when one or more reactive properties of the class change. It bridges the gap between object-oriented state management and React's declarative rendering model.
It uses useSyncExternalStore under the hood to ensure reactivity and avoid tearing.
Example
import { useReactiveInstance } from '@dxbox/use-less-react/client';
import { PubSub, Notifies } from '@dxbox/use-less-react/classes';
class Counter extends PubSub {
count = 0;
@Notifies('count')
increment() {
this.count++;
}
}
export function CounterComponent() {
const { state: count, instance } = useReactiveInstance(
() => new Counter(),
(instance) => instance.count,
['count'] // the dependencies
);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => instance.increment()}>+</button>
</div>
);
}
Parameters
const { state, instance } = useReactiveInstance<
TClass extends Subscribable,
K extends (keyof TClass)[],
RType extends SnapshotProps,
>(
instanceGetter: TClass | (() => TClass),
getSnapshot: GetSnapshot<TClass, RType>,
dependencies: K,
);
| Parameter | Type | Required | Description |
|---|---|---|---|
instanceGetter | TClass | (() => TClass) | ✅ | An instance, or a function returning a new instance. If a function is passed, it's invoked only once per component lifecycle. |
getSnapshot | GetSnapshot<TClass, RType> | ✅ | A function returning a state made of primitive values or objects/arrays of primitives. |
dependencies | (keyof TClass)[] | ✅ | The list of reactive property keys you want the component to listen to. |
Return type
| Property | Type | Description |
|---|---|---|
state | RType | The snapshot returned by the getSnapshot function. |
instance | TClass | The original instance of the reactive class. Use it to call methods or read non-reactive fields. |
Notes
useReactiveInstancedoes not modify the class itself — it only listens to property notifications.- You can safely use multiple instances of the same reactive class in different components.
- Works seamlessly with
ImmutableClassandDependsOndecorators.
Next: See createGenericContext for context utilities.
Migration: See v1.0 useReactiveValues for the modern equivalent.