UNPKG

react-hook-on-screen

Version:

A simple and performatic react hook to trigger a callback when a component become visible on the screen

23 lines (22 loc) 849 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = require("react"); // eslint-disable-next-line @typescript-eslint/no-explicit-any function useOnScreen(ref) { const [isIntersecting, setIntersecting] = (0, react_1.useState)(false); const observer = (0, react_1.useMemo)(() => new IntersectionObserver(([entry]) => setIntersecting(entry.isIntersecting)), []); (0, react_1.useEffect)(() => { observer.observe(ref.current); return () => { observer.disconnect(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); (0, react_1.useEffect)(() => { if (isIntersecting) { observer.unobserve(ref.current); } }, [isIntersecting, observer, ref]); return isIntersecting; } exports.default = useOnScreen;