useIntersectionObserver
The Intersection Observer API allows you to configure a callback that is called whenever an element intersects either the device viewport.
Date: 2021-10-19
The Intersection Observer API allows you to configure a callback that is called whenever an element, called the target, intersects either the device viewport or a specified element; for the purpose of this API, this is called the root element or root.
- rootMargin: Margin around the root. Serves to grow or shrink each side of the root element's bounding box before computing intersections.
- threshold: at what percentage of the target's visibility the observer's callback should be executed.
import { useEffect } from 'react';
const useIntersectionObserver = ({
target,
onIntersect, // callback
threshold = 0.2, // when 20% visible
rootMargin = '0px', // don't adjust viewport margin
}) => {
useEffect(() => {
if (!target) {
return;
}
const observer = new IntersectionObserver(onIntersect, {
rootMargin,
threshold,
});
// Once you have created the observer, you need to give it a target element to watch
const current = target.current;
observer.observe(current);
// clean up our observer
return () => {
observer.unobserve(current);
};
});
};
export default useIntersectionObserver;
<GitGist
gistURL={
'https://gist.githubusercontent.com/dstroot/94c152da31201f41ee8b550442ddbc0b/raw/3a23e00f7c861fe9d36d9e12289a6904ce2ad15e/useIntersectionObserver.js'
}
/>