Skip to content

Instantly share code, notes, and snippets.

@louis-young
Created March 22, 2023 14:07
Show Gist options
  • Save louis-young/45b3aefcd3f5be69c93aabb78750a6e1 to your computer and use it in GitHub Desktop.
Save louis-young/45b3aefcd3f5be69c93aabb78750a6e1 to your computer and use it in GitHub Desktop.
useIntersectionObserver
import { useEffect } from "react";
import type { UseIntersectionObserverParameters } from "./types";
export const useIntersectionObserver = ({
observableRef,
callback,
options,
}: UseIntersectionObserverParameters) => {
useEffect(() => {
const intersectionObserver = new IntersectionObserver(
([{ isIntersecting }]) => {
if (isIntersecting) {
callback();
}
},
{
rootMargin: "500px",
threshold: 0,
...options,
}
);
if (observableRef.current) {
intersectionObserver.observe(observableRef.current);
}
return () => {
if (observableRef.current) {
intersectionObserver.unobserve(observableRef.current);
}
};
}, [callback]);
};
import type { RefObject } from "react";
export interface UseIntersectionObserverParameters {
observableRef: RefObject<HTMLElement>;
callback: () => void;
options?: IntersectionObserverInit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment