| 18 | * @param externalState React.ComponentState[] |
| 19 | */ |
| 20 | const useObserver: UseObserver = ( |
| 21 | callback, |
| 22 | { root, rootMargin, threshold } = {}, |
| 23 | externalState = [], |
| 24 | ) => { |
| 25 | |
| 26 | const target = useRef<Element | null>(null); |
| 27 | const observer = useRef<IntersectionObserver | null>(null); |
| 28 | |
| 29 | const setTarget = useCallback((node) => { |
| 30 | if (target.current && observer.current) { |
| 31 | observer.current.unobserve(target.current); |
| 32 | observer.current.disconnect(); |
| 33 | observer.current = null; |
| 34 | } |
| 35 | |
| 36 | if (node) { |
| 37 | observer.current = new IntersectionObserver(callback, { root, rootMargin, threshold }); |
| 38 | observer.current.observe(node); |
| 39 | target.current = node; |
| 40 | } |
| 41 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 42 | }, [target, root, rootMargin, threshold, ...externalState]); |
| 43 | |
| 44 | return setTarget; |
| 45 | }; |
| 46 | |
| 47 | export default useObserver; |