( ref: RefObject<HTMLElement>, options: IntersectionObserverInit )
| 2 | import { RefObject, useEffect, useState } from "react"; |
| 3 | |
| 4 | const useIntersection = ( |
| 5 | ref: RefObject<HTMLElement>, |
| 6 | options: IntersectionObserverInit |
| 7 | ): IntersectionObserverEntry | null => { |
| 8 | const [intersectionObserverEntry, setIntersectionObserverEntry] = |
| 9 | useState<IntersectionObserverEntry | null>(null); |
| 10 | |
| 11 | useEffect(() => { |
| 12 | if (ref.current && typeof IntersectionObserver === "function") { |
| 13 | const handler = (entries: IntersectionObserverEntry[]) => { |
| 14 | setIntersectionObserverEntry(entries[0]); |
| 15 | }; |
| 16 | |
| 17 | const observer = new IntersectionObserver(handler, options); |
| 18 | observer.observe(ref.current); |
| 19 | |
| 20 | return () => { |
| 21 | setIntersectionObserverEntry(null); |
| 22 | observer.disconnect(); |
| 23 | }; |
| 24 | } |
| 25 | // eslint-disable-next-line @typescript-eslint/no-empty-function |
| 26 | return () => {}; |
| 27 | }, [ref.current, options.threshold, options.root, options.rootMargin]); |
| 28 | |
| 29 | return intersectionObserverEntry; |
| 30 | }; |
| 31 | |
| 32 | export default useIntersection; |
no outgoing calls
no test coverage detected