DEV Community

Rolando Gómez Tabar
Rolando Gómez Tabar

Posted on

4 3

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay