UNPKG

@acrool/react-hooks

Version:

Common javascript utils methods for project development

77 lines (76 loc) 1.83 kB
import { useRef as g, useTransition as y, useState as s, useEffect as P, useCallback as R } from "react"; const p = ({ enabled: o, imageUrl: n }) => { const t = g(null), e = g(null), [, a] = y(), [c, i] = s(!1), [u, f] = s(!0), [l, h] = s(!1), [w, E] = s(); P(() => (o && t.current && n && (e.current = new window.IntersectionObserver(F), e.current.observe(t.current)), () => { e.current && e.current.disconnect(); }), [n, o]); const O = () => { a(() => { i(!0); }); }, I = () => { a(() => { i(!1), f(!1), h(!0); }); }, v = () => { a(() => { i(!1), f(!1), E(n); }); }, F = R((L, d) => { for (let r of L) if (r.isIntersecting) { const T = r.target; if (d.unobserve(T), O(), n) { const b = new Image(); b.src = n, b.onload = v, b.onerror = I; } } }, [n]); return { imageRef: t, _imageUrl: w, isPending: u, isFetching: c, isError: l }; }, z = ({ enabled: o, imageUrl: n }) => { const t = g(null), e = g(null), [a, c] = y(), [i, u] = s(!1), [f, l] = s(!0), [h, w] = s(!1); P(() => (o && t.current && n && (e.current = new window.IntersectionObserver(v), e.current.observe(t.current)), () => { e.current && e.current.disconnect(); }), [n, o]); const E = () => { c(() => { u(!0); }); }, O = () => { c(() => { u(!1), l(!1), w(!0); }); }, I = () => { c(() => { u(!1), l(!1); }); }, v = R((F, L) => { for (let d of F) if (d.isIntersecting) { const r = d.target; L.unobserve(r), E(), r.src = n, r.onload = I, r.onerror = O; } }, [n]); return { imageRef: t, isPending: f, isFetching: i, isError: h }; }; export { p as useLazyLoadBackground, z as useLazyLoadImage };