Skip to content
stoic man

useObservable

A simple TypeScript hook for subscribing to a BehaviorSubject with React Hooks

useObservable.ts
function useObservable<T>(observable: BehaviorSubject<T>): T {
  let observableRef = useRef<BehaviorSubject<T>>(observable);
 
  if (observableRef.current !== observable) {
    observableRef.current = observable;
  }
 
  const subscribe = useCallback((handleStoreChange: VoidFunction) => {
    const subscription = observableRef.current.subscribe(handleStoreChange);
    return () => subscription.unsubscribe();
  }, []);
 
  const getSnapshot = useCallback(() => {
    return observableRef.current.getValue();
  }, []);
  return useSyncExternalStore(subscribe, getSnapshot);
}

All snippets