From 052aa23bbcf551502c6c715878f23d0c29569398 Mon Sep 17 00:00:00 2001 From: gabrieljablonski <contact@gabrieljablonski.com> Date: Wed, 22 Feb 2023 11:38:48 -0300 Subject: [PATCH] fix: `useLayoutEffect` workaround for ssr --- src/components/Tooltip/Tooltip.tsx | 5 +++-- src/utils/use-isomorphic-layout-effect.ts | 5 +++++ 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 src/utils/use-isomorphic-layout-effect.ts diff --git a/src/components/Tooltip/Tooltip.tsx b/src/components/Tooltip/Tooltip.tsx index b40e0ada..58771025 100644 --- a/src/components/Tooltip/Tooltip.tsx +++ b/src/components/Tooltip/Tooltip.tsx @@ -1,8 +1,9 @@ -import { useEffect, useState, useRef, useLayoutEffect } from 'react' +import { useEffect, useState, useRef } from 'react' import classNames from 'classnames' import debounce from 'utils/debounce' import { TooltipContent } from 'components/TooltipContent' import { useTooltip } from 'components/TooltipProvider' +import useIsomorphicLayoutEffect from 'utils/use-isomorphic-layout-effect' import { computeTooltipPosition } from '../../utils/compute-positions' import styles from './styles.module.css' import type { IPosition, ITooltip } from './TooltipTypes' @@ -63,7 +64,7 @@ const Tooltip = ({ * but should be used carefully because of caveats * https://beta.reactjs.org/reference/react/useLayoutEffect#caveats */ - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { mounted.current = true return () => { mounted.current = false diff --git a/src/utils/use-isomorphic-layout-effect.ts b/src/utils/use-isomorphic-layout-effect.ts new file mode 100644 index 00000000..c50228bd --- /dev/null +++ b/src/utils/use-isomorphic-layout-effect.ts @@ -0,0 +1,5 @@ +import { useLayoutEffect, useEffect } from 'react' + +const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect + +export default useIsomorphicLayoutEffect