Last active
February 15, 2024 23:00
-
-
Save euxn23/3a0752436f357d99eb133b5a4126173b to your computer and use it in GitHub Desktop.
use-behavior-subject.ts
This file contains hidden or 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 { BehaviorSubject } from 'rxjs' | |
| import { useSyncExternalStore } from 'react' | |
| export function useSyncBehaviorSubject<T>(subject: BehaviorSubject<T>): T { | |
| return useSyncExternalStore( | |
| (onStoreChange) => { | |
| const subscription = subject.subscribe(onStoreChange) | |
| return () => subscription.unsubscribe() | |
| }, | |
| () => subject.value | |
| ) | |
| } | |
| export function setBehaviorSubjectValue<T>(subject: BehaviorSubject<T>): (value: T) => void { | |
| return (value: T) => subject.next(value) | |
| } |
This file contains hidden or 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
| // for NOT ONLY React | |
| export const model = new BehaviorSubject<Model>({}) | |
| export const setModel = setBehaviorSubjectValue(model) | |
| // for ONLY React | |
| export const useModel = () => useSyncBehaviorSubject(model) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment