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

useIntersectionObserver.js

38 lines665 Bytes

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