Created
June 12, 2024 11:50
-
-
Save Ebrahim-Ramadan/672b49843437b8971f86c368cf3d42a5 to your computer and use it in GitHub Desktop.
Nextjs component handling the visibility detection using the Intersection Observer js web standard API. This cuold help reduce the initial amount of bytes sent thru the first glance to the browser.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use client'; | |
import { useEffect, useRef, useState } from 'react'; | |
export const LazyLoad = ({ children }) => { | |
const [isVisible, setIsVisible] = useState(false); | |
const ref = useRef(); | |
useEffect(() => { | |
const observer = new IntersectionObserver( | |
([entry]) => { | |
if (entry.isIntersecting) { | |
setIsVisible(true); | |
observer.disconnect(); | |
} | |
}, | |
{ rootMargin: '100px' } //the root margin | |
); | |
if (ref.current) { | |
observer.observe(ref.current); | |
} | |
return () => { | |
if (ref.current) { | |
observer.unobserve(ref.current); | |
} | |
}; | |
}, []); | |
return <div | |
className='min-h-screen w-full flex flex-col items-center justify-center' | |
ref={ref}>{isVisible ? children : null}</div>; | |
}; | |
export default LazyLoad; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment