Skip to content

Instantly share code, notes, and snippets.

@Ebrahim-Ramadan
Created June 12, 2024 11:50
Show Gist options
  • Save Ebrahim-Ramadan/672b49843437b8971f86c368cf3d42a5 to your computer and use it in GitHub Desktop.
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.
'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