Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The Intersection Observer API allows you to configure a callback that is called whenever an element intersects either the device viewport.
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment