UNPKG

ez-observable

Version:

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

37 lines (36 loc) 1.06 kB
/** * Wraps a class instance in a reactive proxy for use inside React components. * Whenever you read a field decorated with `@observable`, the hook * automatically subscribes to changes on that specific field, so your component * only re-renders when the values you actually access are updated. * * Under the hood, `useObserved` returns a Proxy of your object. It tracks * property reads during render and sets up listeners for those keys. * When one of those keys changes, the hook forces the component to re-render. * * Usage: * ```typescript * 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> * ); * }; * ``` */ export declare function useObserved<T extends object>(target: T): T;