From 557c6cb26a356249d70f41d7b87ce5e251922b60 Mon Sep 17 00:00:00 2001 From: Pas <74743263+Pasithea0@users.noreply.github.com> Date: Fri, 28 Feb 2025 22:20:35 -0700 Subject: [PATCH] unload off screen carousels --- .../discover/components/LazyMediaCarousel.tsx | 5 ++-- .../hooks/useIntersectionObserver.tsx | 28 +++++++++---------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/pages/discover/components/LazyMediaCarousel.tsx b/src/pages/discover/components/LazyMediaCarousel.tsx index 527bbbbf..67594d24 100644 --- a/src/pages/discover/components/LazyMediaCarousel.tsx +++ b/src/pages/discover/components/LazyMediaCarousel.tsx @@ -26,9 +26,8 @@ export function LazyMediaCarousel({ const [medias, setMedias] = useState([]); // Use intersection observer to detect when this component is visible - const { targetRef, isIntersecting, hasIntersected } = useIntersectionObserver( + const { targetRef, isIntersecting } = useIntersectionObserver( { rootMargin: "200px" }, // Load when within 200px of viewport - true, // Only trigger once ); // Use the lazy loading hook to fetch data when visible @@ -36,7 +35,7 @@ export function LazyMediaCarousel({ genre || null, category || null, mediaType, - hasIntersected, + isIntersecting, ); // Update medias when data is loaded diff --git a/src/pages/discover/hooks/useIntersectionObserver.tsx b/src/pages/discover/hooks/useIntersectionObserver.tsx index 5d9850b5..1e817410 100644 --- a/src/pages/discover/hooks/useIntersectionObserver.tsx +++ b/src/pages/discover/hooks/useIntersectionObserver.tsx @@ -8,20 +8,24 @@ interface IntersectionObserverOptions { export function useIntersectionObserver( options: IntersectionObserverOptions = {}, - onceOnly = false, ) { const [isIntersecting, setIsIntersecting] = useState(false); const [hasIntersected, setHasIntersected] = useState(false); const targetRef = useRef(null); useEffect(() => { - const observer = new IntersectionObserver(([entry]) => { - setIsIntersecting(entry.isIntersecting); - - if (entry.isIntersecting && !hasIntersected) { - setHasIntersected(true); - } - }, options); + const observer = new IntersectionObserver( + ([entry]) => { + setIsIntersecting(entry.isIntersecting); + if (entry.isIntersecting) { + setHasIntersected(true); + } + }, + { + ...options, + rootMargin: options.rootMargin || "200px 0px", + }, + ); const currentTarget = targetRef.current; if (currentTarget) { @@ -33,11 +37,7 @@ export function useIntersectionObserver( observer.unobserve(currentTarget); } }; - }, [options, hasIntersected]); + }, [options]); - // If onceOnly is true, we only care if it has ever intersected - // Otherwise, we care about the current intersection state - const shouldLoad = onceOnly ? hasIntersected : isIntersecting; - - return { targetRef, isIntersecting: shouldLoad, hasIntersected }; + return { targetRef, isIntersecting, hasIntersected }; }