Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useIntersectionObserver.js

33 lines598 Bytes

1import React from 'react'
2​
3export default function useIntersectionObserver({
4 root,
5 target,
6 onIntersect,
7 threshold = 1.0,
8 rootMargin = '0px',
9}) {
10 React.useEffect(() => {
11 const observer = new IntersectionObserver(
12 entries =>
13 entries.forEach(entry => entry.isIntersecting && onIntersect()),
14 {
15 root: root && root.current,
16 rootMargin,
17 threshold,
18 }
19 )
20​
21 const el = target && target.current
22​
23 if (!el) {
24 return
25 }
26​
27 observer.observe(el)
28​
29 return () => {
30 observer.unobserve(el)
31 }
32 }, [target.current])