From 87d1132090fb8d4d6b773f4efe91ea3caa326b30 Mon Sep 17 00:00:00 2001 From: Yu Yi Yang Date: Fri, 23 Aug 2024 17:39:04 +0200 Subject: [PATCH] add useIsVisible hook for table height --- src/Containers/NetworkTableContainer.jsx | 6 ++++-- src/hooks/useIsVisible.js | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 src/hooks/useIsVisible.js diff --git a/src/Containers/NetworkTableContainer.jsx b/src/Containers/NetworkTableContainer.jsx index 5de49fa..76ff8ce 100644 --- a/src/Containers/NetworkTableContainer.jsx +++ b/src/Containers/NetworkTableContainer.jsx @@ -10,6 +10,7 @@ import { useTheme } from '../state/theme/Context'; import InputHAR from '../Components/Import/InputHAR'; import NetworkTableBody from '../Components/NetworkTable/NetworkTableBody'; import { TABLE_HEADER_HEIGHT } from '../constants'; +import { useIsVisible } from '../hooks/useIsVisible'; const context = classNames.bind(Styles); @@ -22,12 +23,13 @@ const NetworkTableContainer = () => { const [tableBodyHeight, setTableBodyHeight] = useState(0); const ref = useRef(null); + const isVisible = useIsVisible(ref); useEffect(() => { - if (ref?.current) { + if (ref?.current && isVisible) { setTableBodyHeight(ref.current.clientHeight - TABLE_HEADER_HEIGHT); } - }, [ref, actualData]); + }, [ref, actualData, isVisible]); if (error) { return ( diff --git a/src/hooks/useIsVisible.js b/src/hooks/useIsVisible.js new file mode 100644 index 0000000..eeb9742 --- /dev/null +++ b/src/hooks/useIsVisible.js @@ -0,0 +1,19 @@ +import { useEffect, useMemo, useState } from 'react'; + +export const useIsVisible = (elementRef) => { + const [isIntersecting, setIntersecting] = useState(false); + + const observer = useMemo(() => new IntersectionObserver( + ([entry]) => setIntersecting(entry.isIntersecting), + ), [elementRef]); + + useEffect(() => { + if (elementRef?.current) { + observer.observe(elementRef.current); + } + + return () => observer.disconnect(); + }, []); + + return isIntersecting; +};