UNPKG

react-infinite-scroll-smart

Version:

Infinite scroll component for list and reverse list, feed and chats

36 lines (35 loc) 1.44 kB
import { useEffect, useMemo, useRef } from "react"; const useInfiniteScroll = (callback, direction = "bottom", useWindowScroll = false, disabled = false, rootMargin = "100px") => { const sentinelRef = useRef(null); const parentRef = useRef(null); const containerStyles = useMemo(() => { if (direction === "top") { return { display: "flex", flexDirection: "column-reverse" }; } return {}; }, [direction]); useEffect(() => { if (disabled) return; if (!("IntersectionObserver" in window)) return; if (!parentRef.current || !sentinelRef.current) return; const observer = new IntersectionObserver(async (entries) => { if (entries[0].isIntersecting) { const prev = parentRef.current?.scrollHeight || 0; await callback(); const next = parentRef.current?.scrollHeight || 0; if (direction === "top") parentRef.current?.scrollBy(0, next - prev); } }, { root: useWindowScroll ? null : parentRef.current, rootMargin, }); observer.observe(sentinelRef.current); return () => observer.disconnect(); }, [callback, disabled, direction, rootMargin, parentRef, sentinelRef]); return { sentinelRef, parentRef, containerStyles }; }; export default useInfiniteScroll;