Skip to content

Commit

Permalink
fix(HeightAnimation): avoid usage of useLayoutEffect during SSR (#1749)
Browse files Browse the repository at this point in the history
React warns about the usage of `useLayoutEffect` when React renders on the server (SSR).

This behavior can be enabled with the `FAST_DEV` flag in gatsby-config.

One "quick" fix is to use useEffect on the server, which again does nothing there.

The React team has [some options](https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85) to that "problem". We basically use option 1, with this approach.

Any other suggestions?
  • Loading branch information
tujoworker authored Nov 24, 2022
1 parent 00a4ab4 commit 667059b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function isGridVisible() {
}

export function GridActivator() {
React.useLayoutEffect(() => {
React.useEffect(() => {
if (isGridVisible()) {
makeGridVisible()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import React from 'react'
import HeightAnimationInstance from './HeightAnimationInstance'

// SSR warning fix: https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
const useLayoutEffect =
typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect

export type useHeightAnimationOptions = {
/**
* Set to `true`, when initially `false` was given, to animate from 0px to auto.
Expand Down Expand Up @@ -66,7 +70,7 @@ export function useHeightAnimation(

React.useEffect(() => setIsMounted(false), []) // eslint-disable-line

React.useLayoutEffect(() => {
useLayoutEffect(() => {
animRef.current = new HeightAnimationInstance({ animate })

if (isInitialRender && onInit) {
Expand Down Expand Up @@ -139,7 +143,7 @@ export function useHeightAnimation(
}

function useOpenClose({ open, animRef, targetRef, isInitialRender }) {
React.useLayoutEffect(() => {
useLayoutEffect(() => {
if (!targetRef.current) {
return // stop here
}
Expand Down Expand Up @@ -178,7 +182,7 @@ function useAdjust({ children, animRef, isInitialRender }) {
}
}, [children]) // eslint-disable-line react-hooks/exhaustive-deps

React.useLayoutEffect(() => {
useLayoutEffect(() => {
if (shouldAdjust()) {
/**
* Ensure we don't have height, while we get the "toHeight" again
Expand Down

0 comments on commit 667059b

Please sign in to comment.