JAVASCRIPT
Implement Lazy Loading or Scroll Effects with useIntersectionObserver
Create a React hook, `useIntersectionObserver`, to efficiently detect when an element enters or exits the viewport, enabling lazy loading or scroll-based animations.
import { useEffect, useRef, useState } from 'react';
const useIntersectionObserver = (options) => {
const [entry, setEntry] = useState(null);
const observerRef = useRef(null);
const elementRef = useRef(null);
useEffect(() => {
if (elementRef.current && typeof IntersectionObserver === 'function') {
observerRef.current = new IntersectionObserver(([ent]) => {
setEntry(ent);
}, options);
observerRef.current.observe(elementRef.current);
}
return () => {
if (observerRef.current) {
observerRef.current.disconnect();
}
};
}, [options]);
return [elementRef, entry];
};
export default useIntersectionObserver;
How it works: The `useIntersectionObserver` hook provides a ref to attach to any DOM element and returns its intersection entry. It uses the browser's `IntersectionObserver` API to efficiently monitor when the element enters or leaves the viewport, making it ideal for lazy loading components, images, or triggering animations as elements become visible.