Skip to content

Commit

Permalink
fix: Prevent parent from unnecessary updates when scrolling window. (#47
Browse files Browse the repository at this point in the history
)

Co-authored-by: Nikita Bahliuk <[email protected]>
  • Loading branch information
shotmk and Nikita Bahliuk authored Aug 13, 2020
1 parent d40e470 commit 170c136
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/useRect.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand All @@ -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])

Expand All @@ -27,7 +28,9 @@ export default function useRect(nodeRef) {
return
}

const observer = observeRect(element, setRect)
const observer = observeRect(element, rect => {
dispatch({ rect });
});

observer.observe()

Expand All @@ -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;
}

0 comments on commit 170c136

Please sign in to comment.