From 62fc73fde13e59ab1f677cc04172804afb4f99ad Mon Sep 17 00:00:00 2001 From: mymphe Date: Tue, 17 Aug 2021 09:43:39 +0600 Subject: [PATCH] feat: use isomorphic useEffect for server vs client --- packages/hooks/src/useLockScroll.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/hooks/src/useLockScroll.ts b/packages/hooks/src/useLockScroll.ts index 82547abd..a578a093 100644 --- a/packages/hooks/src/useLockScroll.ts +++ b/packages/hooks/src/useLockScroll.ts @@ -1,4 +1,4 @@ -import { useCallback, useLayoutEffect } from 'react' +import { useCallback, useLayoutEffect, useEffect } from 'react' const getScrollbarSize = (): number => { const tempDiv = document.createElement('div') @@ -42,8 +42,12 @@ const setStyleProperty = ( } } -export const useLockScroll = (element: HTMLElement = document.body): void => { +const useIsomorphicLayoutEffect = + typeof window !== 'undefined' ? useLayoutEffect : useEffect + +export const useLockScroll = (target?: HTMLElement): void => { const lockScroll = useCallback(() => { + const element = target ?? document.body if (!isVerticalScroll(element)) return const previousValues = { @@ -63,9 +67,9 @@ export const useLockScroll = (element: HTMLElement = document.body): void => { } return unlockScroll - }, [element]) + }, [target]) - useLayoutEffect(() => { + useIsomorphicLayoutEffect(() => { const unlockScroll = lockScroll() return unlockScroll }, [lockScroll])