From c781f93a9cbc8be64a8aade4e4b068f8b100d5c9 Mon Sep 17 00:00:00 2001 From: Cody Bennett Date: Tue, 9 Apr 2024 06:41:08 -0500 Subject: [PATCH] fix: sidestep react-server warnings for layout effects (#35) --- src/index.tsx | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index 25c9728..3c13720 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,6 +1,20 @@ import * as React from 'react' import type ReactReconciler from 'react-reconciler' +/** + * An SSR-friendly useLayoutEffect. + * + * React currently throws a warning when using useLayoutEffect on the server. + * To get around it, we can conditionally useEffect on the server (no-op) and + * useLayoutEffect elsewhere. + * + * @see https://github.com/facebook/react/issues/14927 + */ +const useIsomorphicLayoutEffect = + typeof window !== 'undefined' && (window.document?.createElement || window.navigator?.product === 'ReactNative') + ? React.useLayoutEffect + : React.useEffect + /** * Represents a react-internal Fiber node. */ @@ -145,7 +159,7 @@ export function useNearestChild( const fiber = useFiber() const childRef = React.useRef() - React.useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { childRef.current = traverseFiber( fiber, false, @@ -168,7 +182,7 @@ export function useNearestParent( const fiber = useFiber() const parentRef = React.useRef() - React.useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { parentRef.current = traverseFiber( fiber, true,