To use the useIntersectionObserver
hook for lazy loading images in React, you can create a custom hook that observes when an image enters the viewport and loads it dynamically. Here's how you can implement it:
jsximport { useEffect, useRef, useState } from 'react';
const useIntersectionObserver = (threshold = 0) => {
const [isVisible, setIsVisible] = useState(false);
const targetRef = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
const [entry] = entries;
setIsVisible(entry.isIntersecting);
},
{ threshold }
);
if (targetRef.current) {
observer.observe(targetRef.current);
}
return () => {
if (targetRef.current) {
observer.unobserve(targetRef.current);
}
};
}, [threshold]);
return [targetRef, isVisible];
};
export default useIntersectionObserver;
In this custom hook:
useState
hook to manage the visibility of the target element (isVisible
).useRef
hook to create a reference to the target element (targetRef
).useEffect
hook to create an IntersectionObserver
instance. When the target element enters the viewport, isVisible
is set to true
.targetRef
and isVisible
. The targetRef
is used to attach the observer to the target element, and isVisible
indicates whether the target element is currently visible in the viewport.You can use this custom hook in your components to lazy load images like this:
jsximport React from 'react';
import useIntersectionObserver from './useIntersectionObserver';
const LazyImage = ({ src, alt }) => {
const [imageRef, isVisible] = useIntersectionObserver();
return (
<img
ref={imageRef}
src={isVisible ? src : ''}
alt={alt}
/>
);
};
export default LazyImage;
In this example, the LazyImage
component uses the useIntersectionObserver
hook to observe when the image enters the viewport. When the image is visible, the src
attribute is set, and the image is loaded dynamically. This technique helps improve performance by only loading images when they are needed. Adjust the hook and component logic as needed for your specific lazy loading requirements