Skip to content

Instantly share code, notes, and snippets.

@lu2000luk
Forked from Rasil07/useIntersection.js
Last active February 8, 2025 14:17
Show Gist options
  • Save lu2000luk/cc1b26bdc5ff33de03ebbfb7f46d2ee3 to your computer and use it in GitHub Desktop.
Save lu2000luk/cc1b26bdc5ff33de03ebbfb7f46d2ee3 to your computer and use it in GitHub Desktop.
React custom hook to observe an element is visible in viewport or not
import { useEffect, useState, useRef } from "react";
export const useIntersection = (element: { current: any }, rootMargin: any) => {
const [isVisible, setState] = useState(false);
useEffect(() => {
const current = element?.current;
const observer = new IntersectionObserver(
([entry]) => {
setState(entry.isIntersecting);
},
{ rootMargin }
);
current && observer?.observe(current);
return () => current && observer.unobserve(current);
}, []);
return isVisible;
};
export const onViewElement = ({ callbackFn, children }: { callbackFn: any; children: any }) => {
const triggerRef = useRef(null);
const isVisible = useIntersection(triggerRef, "0px");
useEffect(() => {
if (isVisible) {
callbackFn();
}
}, [callbackFn, isVisible]);
return (<div ref={triggerRef}>{children}</div>);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment