Skip to content

Instantly share code, notes, and snippets.

@aniketchanana
Created March 25, 2023 13:53
Show Gist options
  • Save aniketchanana/6db11aad8becdef41b0941524f281727 to your computer and use it in GitHub Desktop.
Save aniketchanana/6db11aad8becdef41b0941524f281727 to your computer and use it in GitHub Desktop.
import { MutableRefObject, useEffect } from "react";
type ObserverConfiguration = {
root?: Element | Document | null;
rootMargin?: string; // same CSS like values (It don't effect CSS for element)
threshold?: number | number[];
};
type ObserverOptions = {
configuration?: Partial<ObserverConfiguration>;
callback: (isInterSecting: boolean) => void;
observingElement: MutableRefObject<any>;
};
const DEFAULT_CONFIGURATION: ObserverConfiguration = {
root: null, // take document as root
rootMargin: "0px", // give 0px margin to container
threshold: 0.5, // when 50% of the observed element is intersected
};
const useInterSectionObserver = ({
configuration,
callback,
observingElement,
}: ObserverOptions) => {
useEffect(() => {
if (!observingElement) {
return;
}
const observer = new IntersectionObserver(
(entries: any) => {
const [entry] = entries;
callback(entry.isIntersecting);
},
{
...DEFAULT_CONFIGURATION,
...configuration,
}
);
if (observingElement?.current) observer.observe(observingElement?.current);
return () => {
if (observingElement?.current)
observer.unobserve(observingElement?.current);
};
}, [observingElement]);
};
export default useInterSectionObserver;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment