Created
March 19, 2025 10:59
-
-
Save nokazn/85197b44c9aa6a0fde0af083aa360f1e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { type MutableRefObject, useEffect, useRef } from "react"; | |
| type Props<T> = { | |
| elementRef: MutableRefObject<T | null>; | |
| callback: (entry: IntersectionObserverEntry) => void; | |
| options?: IntersectionObserverInit; | |
| }; | |
| export const useIntersectionObserver = <T extends HTMLElement>({ | |
| elementRef, | |
| callback, | |
| options, | |
| }: Props<T>) => { | |
| const savedCallback = useRef(callback); | |
| useEffect(() => { | |
| savedCallback.current = callback; | |
| }, [callback]); | |
| useEffect(() => { | |
| if (!elementRef.current || typeof IntersectionObserver === "undefined") { | |
| return; | |
| } | |
| const observer = new IntersectionObserver((entries) => { | |
| entries.forEach((entry) => { | |
| savedCallback.current?.(entry); | |
| }); | |
| }, options); | |
| observer.observe(elementRef.current); | |
| return () => { | |
| observer.disconnect(); | |
| }; | |
| }, [elementRef, options]); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment