27 lines
1.0 KiB
JavaScript
27 lines
1.0 KiB
JavaScript
import { useRef, useCallback } from "react";
|
|
|
|
/**
|
|
* Универсальный хук для бесконечного скролла через IntersectionObserver.
|
|
* Возвращает ref, который нужно повесить на сентинел-элемент в конце списка.
|
|
*
|
|
* @param {Function} onIntersect — вызывается, когда сентинел попадает в вьюпорт
|
|
* @param {boolean} enabled — можно ли сейчас триггерить подгрузку
|
|
*/
|
|
export function useInfiniteScroll(onIntersect, enabled) {
|
|
const observerRef = useRef(null);
|
|
|
|
const sentinelRef = useCallback(node => {
|
|
if (!enabled) return;
|
|
if (observerRef.current) observerRef.current.disconnect();
|
|
|
|
observerRef.current = new IntersectionObserver(entries => {
|
|
if (entries[0].isIntersecting && enabled) {
|
|
onIntersect();
|
|
}
|
|
}, { rootMargin: "200px" });
|
|
|
|
if (node) observerRef.current.observe(node);
|
|
}, [enabled, onIntersect]);
|
|
|
|
return sentinelRef;
|
|
} |