Skip to content

Commit 170c136

Browse files
shotmkNikita Bahliuk
andauthored
fix: Prevent parent from unnecessary updates when scrolling window. (#47)
Co-authored-by: Nikita Bahliuk <[email protected]>
1 parent d40e470 commit 170c136

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/useRect.js

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect'
66

77
export default function useRect(nodeRef) {
88
const [element, setElement] = React.useState(nodeRef.current)
9-
const [rect, setRect] = React.useState(null)
9+
const [rect, dispatch] = React.useReducer(rectReducer, null);
1010
const initialRectSet = React.useRef(false)
1111

1212
useIsomorphicLayoutEffect(() => {
@@ -18,7 +18,8 @@ export default function useRect(nodeRef) {
1818
useIsomorphicLayoutEffect(() => {
1919
if (element && !initialRectSet.current) {
2020
initialRectSet.current = true
21-
setRect(element.getBoundingClientRect())
21+
const rect = element.getBoundingClientRect();
22+
dispatch({ rect });
2223
}
2324
}, [element])
2425

@@ -27,7 +28,9 @@ export default function useRect(nodeRef) {
2728
return
2829
}
2930

30-
const observer = observeRect(element, setRect)
31+
const observer = observeRect(element, rect => {
32+
dispatch({ rect });
33+
});
3134

3235
observer.observe()
3336

@@ -38,3 +41,12 @@ export default function useRect(nodeRef) {
3841

3942
return rect
4043
}
44+
45+
function rectReducer(state, action) {
46+
const rect = action.rect;
47+
if (!state || state.height !== rect.height || state.width !== rect.width) {
48+
return rect;
49+
}
50+
return state;
51+
}
52+

0 commit comments

Comments
 (0)