Created
September 30, 2023 03:07
-
-
Save saintplay/d3c8f0fe090990110c0e5f91d50d9f1e to your computer and use it in GitHub Desktop.
useObservableState.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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