UNPKG

react-laze

Version:
87 lines (80 loc) 2.07 kB
// src/useLaze.ts import { useDebugValue as useDebugValue4, useEffect, useState as useState2 } from "react"; // src/useReactiveRef.ts import { useDebugValue as useDebugValue3, useState } from "react"; // src/useConstant.ts import { useDebugValue as useDebugValue2 } from "react"; // src/useLazyRef.ts import { useDebugValue, useRef } from "react"; function useLazyRef(supplier) { const ref = useRef(); if (!ref.current) { ref.current = { current: supplier() }; } useDebugValue(ref.current); return ref.current; } // src/useConstant.ts function useConstant(supplier) { const { current } = useLazyRef(supplier); useDebugValue2(current); return current; } // src/useReactiveRef.ts function useReactiveRef(supplier) { const [state, setState] = useState(supplier); const ref = useLazyRef(supplier); if (ref.current !== state) { ref.current = state; } const proxyObject = useConstant(() => ({ get current() { return ref.current; }, set current(value) { setState(() => value); } })); useDebugValue3(proxyObject); return proxyObject; } // src/useLaze.ts function useLaze(options) { const [visible, setVisible] = useState2(false); const ref = useReactiveRef(() => null); const { current } = ref; const shouldRefresh = options == null ? void 0 : options.refresh; useEffect(() => { setVisible(false); if (current) { const observer = new IntersectionObserver((entries) => { for (const entry of entries) { if (shouldRefresh) { setVisible(entry.isIntersecting); } else if (entry.isIntersecting) { setVisible(true); observer.disconnect(); } } }); observer.observe(current); return () => { observer.unobserve(current); observer.disconnect(); }; } return void 0; }, [current, shouldRefresh]); const value = { ref, visible }; useDebugValue4(value); return value; } export { useLaze as default }; //# sourceMappingURL=index.mjs.map