Created
January 30, 2024 13:40
-
-
Save hypersnob/9fe0e3c4df5eb5466172baed54f06a67 to your computer and use it in GitHub Desktop.
Custom React hook that observes a target element and executes a callback when it becomes visible.
This file contains 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 { useEffect, useRef } from "react"; | |
export default function useIntersectionObserver( | |
el: HTMLElement | null, | |
callback: (entry: IntersectionObserverEntry) => void, | |
options: IntersectionObserverInit & { | |
enabled: boolean; | |
} = { | |
root: null, | |
threshold: 0.4, | |
rootMargin: "0px", | |
enabled: true, | |
} | |
) { | |
const observer = useRef<IntersectionObserver | null>(null); | |
useEffect(() => { | |
if (!el || !options.enabled) { | |
return; | |
} | |
observer.current = new IntersectionObserver(([entry]) => { | |
if (entry) { | |
callback(entry); | |
} | |
}, options); | |
observer.current.observe(el); | |
return () => { | |
if (observer.current) { | |
observer.current.disconnect(); | |
} | |
}; | |
}, [el, callback, options.enabled]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment