useIntersectionObserver
A React hook that tracks when an element enters or leaves the viewport, enabling features like lazy loading, infinite scroll, and scroll-based animations.
Demo
1. Lazy Loading Images
2. Scroll Animations
Card 1
This card animates when it enters the viewport. Try scrolling up and down to see the effect.
Card 2
This card animates when it enters the viewport. Try scrolling up and down to see the effect.
Card 3
This card animates when it enters the viewport. Try scrolling up and down to see the effect.
3. Infinite Scroll
Installation
npm install @thibault.sh/hooks
Usage
import { useIntersectionObserver } from "@thibault.sh/hooks";
function LazyComponent() {
const elementRef = useRef(null);
const entry = useIntersectionObserver(elementRef, {
threshold: 0.5,
rootMargin: "100px",
freezeOnceVisible: true,
});
return (
<div ref={elementRef}>
{entry?.isIntersecting && <div>Content is visible!</div>}
</div>
);
}
API Reference
Returns
IntersectionObserverEntry if available, null otherwise
Parameters
elementRef
A React ref object created with useRef() that points to the DOM element you want to observe.
options
A number or array of numbers between 0 and 1, indicating at what percentage of the target's visibility the observer's callback should be executed.
The element that is used as the viewport for checking visibility of the target. Defaults to the browser viewport if not specified.
Margin around the root element. Can have values similar to the CSS margin property. Defaults to "0px".
If true, stops observing the element after it becomes visible once. Useful for optimization in cases like lazy loading.
Return Value
Returns an IntersectionObserverEntry object or null. The entry object contains information about the intersection between the target element and its root container at a specific moment of transition.
- isIntersecting: Boolean indicating if the element is intersecting with the root
- intersectionRatio: Number between 0 and 1 indicating how much of the element is visible
- boundingClientRect: The target element's bounding rectangle
- intersectionRect: The intersection between the target and root
- time: Timestamp when the intersection was recorded
Features
Lazy Loading
Efficiently load images, videos, or components only when they're about to enter the viewport, improving initial page load performance.
Infinite Scroll
Implement infinite scrolling by detecting when the user reaches the bottom of the content and loading more items automatically.
Scroll Animations
Create engaging scroll-based animations by triggering effects when elements come into view, enhancing user experience.
Performance Optimized
Uses the native IntersectionObserver API for efficient viewport tracking without affecting scroll performance.