DEV Community

Rolando Gómez Tabar
Rolando Gómez Tabar

Posted on

How to use React useSyncExternalStore hook and RxJS together

After discovering the useSubscription a while ago and using along with RxJS, it required at least two statements to use it with Rx.BehaviorSubject, create the subscription object and then call useSubscription(subscription):

// create the subscription object
const subscription = useMemo(
  () => ({
    getCurrentValue: () => behaviorSubject.getValue(),
    subscribe: callback => {
      const subscription = behaviorSubject.subscribe(callback);
      return () => subscription.unsubscribe();

  // Re-subscribe any time the behaviorSubject changes
// call the hook
const value = useSubscription(subscription);
Enter fullscreen mode Exit fullscreen mode

See the details here

With this new useSyncExternalStore hook, you have it simpler and integrated in React since version 18.1.0:

const counter$ = new BehaviorSubject(0);

function useCounter() {
  const count = useSyncExternalStore(
      (callback) => {
        const subscription = counter$.subscribe(callback);
        return () => subscription.unsubscribe();
    () => counter$.getValue()
  return count;
Enter fullscreen mode Exit fullscreen mode

As we saw, you still have to wrap the subscribe handler function in a useCallback hook, to prevent the re-subscription and unsubscribe on every change or render.

See a the full example here:

Top comments (0)