ez-observable
v1.0.0
Published
Make class fields reactive in React with a single decorator + hook
Maintainers
Readme
👀 ez-observable
A tiny, easy-to-use library that makes class fields reactive in React. Just add the @observable decorator to your class fields, wrap your instance with the useObserved hook, and your component will automatically re-render when those properties change. No HOCs, no boilerplate.
Why ez-observable?
- Super light: no proxies for every property, only accessors you mark.
- No HOCs: just a hook and a decorator.
- Fast updates: re-renders only when you actually use a property.
- Zero configuration: works out of the box with Stage 3 decorators.
📦 Install
npm install ez-observable
# or
yarn add ez-observable🎩 @observable decorator
Mark a class field so that changes to its value can be tracked by React. Only public instance accessors (not static) are supported.
import { observable } from 'ez-observable';
class Counter {
@observable accessor count: number = 0;
}
const c = new Counter();
c.count = 5; // any hooked components will update⚛️ useObserved hook
Turn your class instance into a reactive proxy for use in a React component. The hook watches only the specific @observable fields you read during render, and triggers a re-render when any of those values change.
import { observable, useObserved } from 'ez-observable';
class Counter {
@observable accessor count: number = 0;
increment() {
this.count++;
}
}
const c = new Counter();
const CounterCompo = () => {
// Only `count` reads will be tracked
const { count } = useObserved(counter);
return (
<div>
<button onClick={() => counter.increment()}>+1</button>
<p>{count}</p>
</div>
);
};