Blog>
Snippets

Integrating with Observable Data Sources Like RxJS

Showcase a use case where useSyncExternalStore is integrated with an RxJS observable to provide real-time updates to a React component.
import { useSyncExternalStore } from 'react';
import { Observable } from 'rxjs';
Importing the required functions from 'react' and the 'Observable' class from 'rxjs' library.
const observable = new Observable(subscriber => {
    // Simulation of some data source that emits a value every second
    const intervalId = setInterval(() => {
        subscriber.next(Math.random());
    }, 1000);
    
    // Cleanup function when the subscription is no longer needed
    return () => clearInterval(intervalId);
});
Creating an RxJS observable that emits a random number every second, and provides a cleanup function to clear the interval when the subscription is no longer needed.
function useObservable(observable) {
    const subscribe = (setState) => {
        const subscription = observable.subscribe(setState);
        return () => subscription.unsubscribe();
    };
    
    const getSnapshot = () => null;
    
    const [state] = useSyncExternalStore(subscribe, getSnapshot);
    
    return state;
}
Creating a custom React hook that uses useSyncExternalStore to subscribe to an RxJS observable. The hook subscribes to the observable, receives updates, and provides an unsubscribe function when the component unmounts.
function MyComponent() {
    const randomValue = useObservable(observable);
    return <div>The latest random value is: {randomValue}</div>;
}
A React component that utilizes the useObservable custom hook to display the latest random number emitted by the observable in real-time.