crimx/observable-hooks

useSubscription and useObservableState cause duplicate requests

jeffmccormick opened this issue · 5 comments

When either hook is used in coordination with ajax.getJSON() (or similar observable), it acts as if 2 subscriptions are made as there are 2 XHR requests made for each hook.

Minimally reproducible example: https://codesandbox.io/s/quizzical-bassi-xcetk?file=/src/App.js

Monitor the network tab to see that 2 requests are made but only 1 state change is triggered. There are several "examples" in the one sandbox to demonstrate the issue.

When using a normal useEffect(() => stream$.subscribe()), everything works as expected.

crimx commented

This happens because of the React Strict Mode which calls certain hooks callbacks twice in development mode only.

It is still safe though(until concurrent mode is ready) but to reduce confusion I will try to make it compatible with Strict Mode.

Good catch. Seems tough considering the "side effect" is caused on subscribe to the observable. Perhaps the useMemo() in useSubscription() can be replaced with a useEffect() that works on a ref to subscription?

As you mentioned, it's not a huge deal since it is only in development mode, so I can proceed as normal. Thanks for such a great library! Let me know if you'd like me to throw a PR at you for this.

crimx commented

Unfortunately this would be a breaking change as useEffect runs in commit phase. useMemo is intentionally used here so that synchronous values from observables can act as initial values. I think it would be best to do this after the React team releases more info about the concurrent mode.

crimx commented

The observable-hooks@alpha is published. There should be no duplicated subscription in strict mode. Please give it a try. Any feedback is welcome!

Updated the sandbox to the alpha and everything looks great! Thank you!