From b2093e822a32ccd8607a9a38e4103a7664798f74 Mon Sep 17 00:00:00 2001 From: Asad Umar Date: Fri, 28 Jan 2022 20:42:02 +0500 Subject: [PATCH] hook made for listening to resize events ie use-on-resize.js, with a debounced callback as to make performance even better. --- ui/component/common/tabs.jsx | 33 +++++++++------------------------ ui/effects/use-on-resize.js | 7 +++---- 2 files changed, 12 insertions(+), 28 deletions(-) diff --git a/ui/component/common/tabs.jsx b/ui/component/common/tabs.jsx index 46f0d679c..9021b3384 100644 --- a/ui/component/common/tabs.jsx +++ b/ui/component/common/tabs.jsx @@ -8,6 +8,7 @@ import { TabPanel as ReachTabPanel, } from '@reach/tabs'; import classnames from 'classnames'; +import { useOnResize } from '../../effects/use-on-resize'; // Tabs are a compound component // The components are used individually, but they will still interact and share state @@ -45,22 +46,14 @@ function Tabs(props: TabsProps) { const [tabsRect, setTabsRect] = React.useState(); // Create a ref of the parent element so we can measure the relative "left" for the bar for the child Tab's - // Don't observe as its going to re-render when the window size changes anyway const tabsRef = useRef(); - function changeWindowSize() { + // Recalculate "Rect" on window resize + useOnResize(() => { if (tabsRef.current) { - setTabsRect(tabsRef.current.getBoundingClientRect() || undefined); + setTabsRect(tabsRef.current.getBoundingClientRect()); } - } - - React.useEffect(() => { - window.addEventListener('resize', changeWindowSize); - - return () => { - window.removeEventListener('resize', changeWindowSize); - }; - }, []); + }); const tabLabels = props.children[0]; const tabContent = props.children[1]; @@ -107,22 +100,14 @@ function Tab(props: TabProps) { const { isSelected } = props; const [rect, setRect] = React.useState(); - function changeWindowSize() { + // Recalculate "Rect" on window resize + useOnResize(() => { if (ref.current) { - setRect(ref.current.getBoundingClientRect() || undefined); + setRect(ref.current.getBoundingClientRect()); } - } - - React.useEffect(() => { - window.addEventListener('resize', changeWindowSize); - - return () => { - window.removeEventListener('resize', changeWindowSize); - }; - }, []); + }); // Each tab measures itself - // Don't observe as its going to re-render when the window size changes anyway const ref = useRef(); // and calls up to the parent when it becomes selected diff --git a/ui/effects/use-on-resize.js b/ui/effects/use-on-resize.js index ed3b463c8..eb4a1edf0 100644 --- a/ui/effects/use-on-resize.js +++ b/ui/effects/use-on-resize.js @@ -1,15 +1,14 @@ import { useEffect } from 'react'; +import debounce from 'util/debounce'; export function useOnResize(cb) { useEffect(() => { - function handleResize() { - cb(); - } + const handleResize = debounce(cb, 100); window.addEventListener('resize', handleResize); handleResize(); return () => window.removeEventListener('resize', handleResize); - }, [cb]); + }, []); }