Skip to content

Instantly share code, notes, and snippets.

@ShaneRich5
Created November 20, 2021 05:47
Show Gist options
  • Save ShaneRich5/6a63b4a3fc99bed4ca03da84ad209c1c to your computer and use it in GitHub Desktop.
Save ShaneRich5/6a63b4a3fc99bed4ca03da84ad209c1c to your computer and use it in GitHub Desktop.
custom hooks
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])
}