reactuals
Version:
A useful package providing a collection of 50+ React hooks and utilities to simplify React development.
21 lines (20 loc) • 713 B
JavaScript
import { useEffect, useState } from "react";
/**
* Detects if a given element is in the viewport.
* @param ref - React ref to the element
* @param rootMargin - Margin around the root (optional)
*/
export function useOnScreen(ref, rootMargin = "0px") {
const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => {
if (!ref.current)
return;
const observer = new IntersectionObserver(([entry]) => setIntersecting(entry.isIntersecting), { rootMargin });
observer.observe(ref.current);
return () => {
if (ref.current)
observer.unobserve(ref.current);
};
}, [ref, rootMargin]);
return isIntersecting;
}