UNPKG

state-management-utilities

Version:
36 lines (35 loc) 1.17 kB
import React from "react"; import { Computed } from "../computed"; import { useDehydrate } from "./dehydrate"; export class ReactComputed extends Computed { _hooks = Object.freeze({ useState: () => { const uid = React.useId(); useDehydrate(); const [state, setInternalState] = React.useState(this.value); React.useEffect(() => { this.register({ uid, callback: (newValue) => setInternalState(newValue), }); return () => { this.unregister({ uid }); }; }, [uid]); const setState = React.useCallback((newState) => { throw new Error("Computed state manager value cannot be set directly.", { cause: { uid: this.uid, }, }); }, []); return [state, setState]; }, }); get hooks() { return this._hooks; } } export function computed(callback, triggers, config) { return new ReactComputed(callback, triggers, config); }