UNPKG

ez-observable

Version:

Make class fields reactive in React with a single decorator + hook

63 lines (45 loc) 1.73 kB
# 👀 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 ```bash 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. ```typescript 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. ```typescript jsx 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> ); }; ```