crimx/observable-hooks

Question: init function call multiple times in StrictMode

xiaoxiangmoe opened this issue · 1 comments

import * as React from "react";
import * as ReactDOM from "react-dom";
import { of } from "rxjs";
import { map } from "rxjs/operators";
import { useObservable, useObservableState } from "observable-hooks";

const { log } = console;

function App() {
  const a = useObservable(() => {
    log("a");
    return of(1);
  });
  const b = useObservable(() => {
    log("b");
    return a.pipe(map((x) => x + 1));
  });

  const [c] = useObservableState(() => {
    log("c");
    return b;
  });
  return <>{c}</>;
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

run codes in development mode and strict mode

It will print

a
b
c
a
b
c

init function in useObservable and useObservableState are called twice.

Is it concurrent mode safe? Is it work as intended?

crimx commented

This is expected. See the React docs for what StrictMode is doing under the hood.

Functions passed to useState is double-invoked under strict mode.

As for the init function, it should be a pure function. So it is still concurrent mode safe. See observable-hooks docs.