JAVASCRIPT
Detect Element Visibility for Lazy Loading with useOnScreen Hook
Implement a useOnScreen React hook to efficiently detect if a DOM element is currently within the viewport, ideal for lazy loading images, components, or triggering animations.
import { useState, useEffect, useRef } from 'react';
function useOnScreen(ref, rootMargin = '0px') {
const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => {
if (!ref.current) return;
const observer = new IntersectionObserver(
([entry]) => {
setIntersecting(entry.isIntersecting);
},
{
rootMargin,
}
);
observer.observe(ref.current);
return () => {
observer.unobserve(ref.current);
};
}, [ref, rootMargin]);
return isIntersecting;
}
// Example Usage:
// function LazyImage({ src, alt }) {
// const imgRef = useRef();
// const isVisible = useOnScreen(imgRef, '100px'); // Trigger 100px before entering viewport
//
// return (
// <img
// ref={imgRef}
// src={isVisible ? src : 'placeholder.jpg'}
// alt={alt}
// style={{ minHeight: '200px', backgroundColor: '#eee' }}
// />
// );
// }
How it works: This `useOnScreen` hook leverages the `IntersectionObserver` API to determine if a referenced DOM element is currently visible within its parent (or the viewport). It's incredibly useful for implementing performance optimizations like lazy loading images or components, triggering animations only when elements come into view, or building infinite scroll features, as it avoids expensive scroll event listeners.