UNPKG

@prokodo/ui

Version:

UI components for production-grade Next.js + Headless CMS (Strapi, Contentful, Headless WordPress) websites by prokodo – built for Core Web Vitals & SEO.

33 lines (32 loc) 1.09 kB
var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); import { useRef, useState, useLayoutEffect } from "react"; function useHydrationReady(opts = {}) { const { enabled = true, ioOptions = { threshold: 0.1 } } = opts; const ref = useRef(null); const [visible, set] = useState(() => { var _a; if (!enabled || typeof window === "undefined") return !enabled; const box = (_a = ref.current) == null ? void 0 : _a.getBoundingClientRect(); return !!box && box.top < window.innerHeight; }); useLayoutEffect(() => { if (!enabled || visible) return; const io = new IntersectionObserver( ([e]) => { if ((e == null ? void 0 : e.isIntersecting) === true) { set(true); io.disconnect(); } }, { ...ioOptions } ); if (ref.current) io.observe(ref.current); return () => io.disconnect(); }, [enabled, visible, ioOptions]); return [visible, ref]; } __name(useHydrationReady, "useHydrationReady"); export { useHydrationReady };