BeTomorrow / micro-observables

A simple Observable library that can be used for easy state management in React applications.
MIT License
104 stars 8 forks source link

React hook useObservable and SSR warnings #32

Open amanteaux opened 1 year ago

amanteaux commented 1 year ago

When useObservable is used in a Server Side rendering context, it raises a React warning:

Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non- hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://reactjs.org/link/uselayouteffect-ssr for common fixes.

To avoid this, the solution described here could be easily applied: https://medium.com/@alexandereardon/uselayouteffect-and-ssr-192986cdcf7a

So for example, the code might look like this:

const useSsrCompatibleLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;

export function useObservable<T>(observable: Observable<T>): T {
  const [, forceRender] = useState({});
  const val = observable.get();

  useSsrCompatibleLayoutEffect(() => {
    return observable.subscribe(() => forceRender({}));
  }, [observable]);

  return val;
}
amanteaux commented 1 year ago

If that is ok, I will gladly make a PR!