From 1c5bd76b9eff825d3d2531c79f5a3af1e9cf2c07 Mon Sep 17 00:00:00 2001 From: Hoyoul Kang Date: Mon, 3 Mar 2025 16:23:52 -0700 Subject: [PATCH] fix: conditionally use useLayoutEffect to avoid react ssr warning --- src/useObservable.ts | 12 ++++++++++-- tsconfig.json | 2 +- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/useObservable.ts b/src/useObservable.ts index 2310d65..9dbddab 100644 --- a/src/useObservable.ts +++ b/src/useObservable.ts @@ -1,11 +1,19 @@ -import { useLayoutEffect, useMemo, useState } from "react"; +import { useEffect, useLayoutEffect, useMemo, useState } from "react"; import { Observable } from "./observable"; +/** + * https://medium.com/@alexandereardon/uselayouteffect-and-ssr-192986cdcf7a + * Ensure that `useLayoutEffect` is exclusively used on the client only to avoid + * React SSR warning. More info at: + * https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85 + */ +const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect; + export function useObservable(observable: Observable): T { const [, forceRender] = useState({}); const val = observable.get(); - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { return observable.subscribe(() => forceRender({})); }, [observable]); diff --git a/tsconfig.json b/tsconfig.json index 914cded..f89d346 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "module": "esnext", - "lib": ["esnext"], + "lib": ["esnext", "dom"], "target": "ES6", "importHelpers": true, "declaration": true,