Skip to content

Instantly share code, notes, and snippets.

@nokazn
Created March 19, 2025 10:59
Show Gist options
  • Select an option

  • Save nokazn/85197b44c9aa6a0fde0af083aa360f1e to your computer and use it in GitHub Desktop.

Select an option

Save nokazn/85197b44c9aa6a0fde0af083aa360f1e to your computer and use it in GitHub Desktop.
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