Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React hook useObservable and SSR warnings #32

Open
amanteaux opened this issue Jan 6, 2023 · 1 comment
Open

React hook useObservable and SSR warnings #32

amanteaux opened this issue Jan 6, 2023 · 1 comment

Comments

@amanteaux
Copy link

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant