Skip to content

Instantly share code, notes, and snippets.

@saintplay
Created September 30, 2023 03:07
Show Gist options
  • Save saintplay/d3c8f0fe090990110c0e5f91d50d9f1e to your computer and use it in GitHub Desktop.
Save saintplay/d3c8f0fe090990110c0e5f91d50d9f1e to your computer and use it in GitHub Desktop.
useObservableState.ts
import { useState, useRef, useEffect } from 'react';
import { BehaviorSubject } from 'rxjs';
export default function useObservableState<TElement>(initialValue: TElement) {
const observableRef = useRef(new BehaviorSubject(initialValue));
const [value, setValue] = useState(initialValue);
useEffect(() => {
observableRef.current.next(value);
}, [value]);
useEffect(() => {
const subscription = observableRef.current.subscribe((newValue) => setValue(newValue));
return () => subscription.unsubscribe();
}, []);
return [value, setValue, observableRef.current] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment