Skip to content

Instantly share code, notes, and snippets.

@dstroot
Created November 6, 2021 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dstroot/94c152da31201f41ee8b550442ddbc0b to your computer and use it in GitHub Desktop.
Save dstroot/94c152da31201f41ee8b550442ddbc0b to your computer and use it in GitHub Desktop.
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