Created
November 6, 2021 00:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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