UNPKG

@equinor/fusion-observable

Version:
31 lines 1.13 kB
import { useCallback, useRef } from 'react'; import { useObservableLayoutSubscription } from './useObservableSubscription'; /** * React hook that keeps a `ref` synchronised with the latest value from an * observable. The ref is updated via a layout-effect subscription so it is * always current during commit phase reads. * * If the observable is a `BehaviorSubject` (or any subject with a `.value` * property), the ref is initialised with that value. * * @template S - The value type. * @param subject - The observable to track. * @param initial - An optional initial value for the ref. * @returns A React ref whose `.current` mirrors the latest emitted value. * * @example * ```tsx * const countRef = useObservableRef(count$); * // countRef.current is always the latest emitted count * ``` */ export const useObservableRef = (subject, initial) => { initial ??= subject.value; const ref = useRef(initial); useObservableLayoutSubscription(subject, useCallback((x) => { ref.current = x; }, [])); return ref; }; export default useObservableRef; //# sourceMappingURL=useObservableRef.js.map