A React Lazy Loading Hook when Image is in View
Overview
I created this hook for my personal website. I wanted to lazy load images when they are in view. I used the IntersectionObserver API to achieve this. Also it was pretty useful when I needed to load more than 850 images in a single page built with react-pageflip.
import React from "react";
export default function useInView(ref: React.RefObject<HTMLDivElement>) {
const [inView, setInView] = React.useState(false);
React.useEffect(() => {
if (!ref.current) return;
const observer = new window.IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
if (inView) {
observer.disconnect();
}
setInView(true);
return;
}
},
{
root: null,
threshold: 0.1,
}
);
observer.observe(ref.current);
return () => {
observer.disconnect();
};
}, [ref]);
return inView;
}