Skip to content

Commit 5791b22

Browse files
committed
feat(useIntersectionObserver): add an IntersectionObserver hook
1 parent ff981fb commit 5791b22

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/useIntersectionObserver.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { useState } from 'react'
2+
3+
import { useStableMemo } from './useStableMemo'
4+
import useEffect from './useIsomorphicEffect'
5+
6+
/**
7+
* Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
8+
* a DOM Element.
9+
*
10+
* @param element The DOM element to observe
11+
* @param init IntersectionObserver options
12+
*/
13+
export default function useIntersectionObserver<TElement extends Element>(
14+
element: TElement | null | undefined,
15+
{ threshold, root, rootMargin }: IntersectionObserverInit = {}
16+
) {
17+
const [entries, setEntry] = useState<IntersectionObserverEntry[] | null>(null)
18+
19+
const observer = useStableMemo(
20+
() => new IntersectionObserver(setEntry, { threshold, root, rootMargin }),
21+
22+
[root, rootMargin, threshold && JSON.stringify(threshold)]
23+
)
24+
25+
useEffect(() => {
26+
if (!element) return
27+
28+
observer.observe(element)
29+
return () => {
30+
observer.unobserve(element)
31+
}
32+
}, [observer, element])
33+
34+
return entries
35+
}

0 commit comments

Comments
 (0)