Created
November 20, 2021 05:47
-
-
Save ShaneRich5/6a63b4a3fc99bed4ca03da84ad209c1c to your computer and use it in GitHub Desktop.
custom hooks
This file contains hidden or 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 React from 'react' | |
export default function useIntersectionObserver({ | |
root, | |
target, | |
onIntersect, | |
threshold = 1.0, | |
rootMargin = '0px', | |
enabled = true, | |
}) { | |
React.useEffect(() => { | |
if (!enabled) { | |
return | |
} | |
const observer = new IntersectionObserver( | |
entries => | |
entries.forEach(entry => entry.isIntersecting && onIntersect()), | |
{ | |
root: root && root.current, | |
rootMargin, | |
threshold, | |
} | |
) | |
const el = target && target.current | |
if (!el) { | |
return | |
} | |
observer.observe(el) | |
return () => { | |
observer.unobserve(el) | |
} | |
}, [target.current, enabled]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copied from https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/load-more-infinite-scroll?from-embed=&file=/hooks/useIntersectionObserver.js:0-665