Skip to content

Commit

Permalink
fix: sidestep react-server warnings for layout effects (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
CodyJasonBennett authored Apr 9, 2024
1 parent bb582c2 commit c781f93
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -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.
*/
Expand Down Expand Up @@ -145,7 +159,7 @@ export function useNearestChild<T = any>(
const fiber = useFiber()
const childRef = React.useRef<T>()

React.useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
childRef.current = traverseFiber<T>(
fiber,
false,
Expand All @@ -168,7 +182,7 @@ export function useNearestParent<T = any>(
const fiber = useFiber()
const parentRef = React.useRef<T>()

React.useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
parentRef.current = traverseFiber<T>(
fiber,
true,
Expand Down

0 comments on commit c781f93

Please sign in to comment.