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
  [behaviorSubject]
);
// call the hook
const value = useSubscription(subscription);
Enter fullscreen mode Exit fullscreen mode

See the details here https://www.npmjs.com/package/use-subscription.

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(
    useCallback(
      (callback) => {
        const subscription = counter$.subscribe(callback);
        return () => subscription.unsubscribe();
      },
      [counter$]
    ),
    () => 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: https://codesandbox.io/s/react18-2-rxjs-s3b781.

Top comments (0)