import type { MutableRefObject, RefObject } from "react"; import { BehaviorSubject } from "rxjs"; import { useState } from "react"; /** * Returns a mutable ref object and a BehaviorSubject. * * Whenever ref.current is changed, the BehaviorSubject will emit the new value. * * @param initialValue The initial value of the BehaviorSubject. */ export function useObservableRef( initialValue: TValue ): [MutableRefObject, BehaviorSubject]; /** * Returns a ref object and a BehaviorSubject. * * Whenever ref.current is changed, the BehaviorSubject will emit the new value. * * @param initialValue The initial value of the BehaviorSubject. */ export function useObservableRef( initialValue: TValue | null ): [RefObject, BehaviorSubject]; /** * Returns a mutable ref object and a BehaviorSubject. * * Whenever ref.current is changed, the BehaviorSubject will emit the new value. * * @param initialValue A optional initial value of the BehaviorSubject. */ export function useObservableRef( initialValue?: TValue ): [MutableRefObject, BehaviorSubject]; export function useObservableRef( initialValue?: TValue ): [MutableRefObject, BehaviorSubject] { const [value$] = useState(() => new BehaviorSubject(initialValue)); const [ref] = useState>(() => ({ get current(): TValue | undefined { return value$.value; }, set current(value: TValue | undefined) { value$.next(value); }, })); return [ref, value$]; }