Skip to content

Instantly share code, notes, and snippets.

@hypersnob
Created January 30, 2024 13:40
Show Gist options
  • Save hypersnob/9fe0e3c4df5eb5466172baed54f06a67 to your computer and use it in GitHub Desktop.
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.
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