From 170c136d92e5410f0fe98978ea8831ff7cc5437f Mon Sep 17 00:00:00 2001 From: shotmk <55147088+shotmk@users.noreply.github.com> Date: Fri, 14 Aug 2020 00:00:46 +0300 Subject: [PATCH] fix: Prevent parent from unnecessary updates when scrolling window. (#47) Co-authored-by: Nikita Bahliuk --- src/useRect.js | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/useRect.js b/src/useRect.js index 05e2d1a9..24b34238 100644 --- a/src/useRect.js +++ b/src/useRect.js @@ -6,7 +6,7 @@ import useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect' export default function useRect(nodeRef) { const [element, setElement] = React.useState(nodeRef.current) - const [rect, setRect] = React.useState(null) + const [rect, dispatch] = React.useReducer(rectReducer, null); const initialRectSet = React.useRef(false) useIsomorphicLayoutEffect(() => { @@ -18,7 +18,8 @@ export default function useRect(nodeRef) { useIsomorphicLayoutEffect(() => { if (element && !initialRectSet.current) { initialRectSet.current = true - setRect(element.getBoundingClientRect()) + const rect = element.getBoundingClientRect(); + dispatch({ rect }); } }, [element]) @@ -27,7 +28,9 @@ export default function useRect(nodeRef) { return } - const observer = observeRect(element, setRect) + const observer = observeRect(element, rect => { + dispatch({ rect }); + }); observer.observe() @@ -38,3 +41,12 @@ export default function useRect(nodeRef) { return rect } + +function rectReducer(state, action) { + const rect = action.rect; + if (!state || state.height !== rect.height || state.width !== rect.width) { + return rect; + } + return state; +} +