useInfiniteScroll trigger callback khi sentinel element xuất hiện trong viewport.
js
function useInfiniteScroll(callback) {
const ref = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) callback();
});
if (ref.current) observer.observe(ref.current);
return () => observer.disconnect();
}, [callback]);
return ref;
}Gán ref cho sentinel element cuối danh sách.
Using IntersectionObserver: function useInfiniteScroll(callback) { const ref = useRef(null); useEffect(() => { const observer = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) callback(); }); if (ref.current) observer.observe(ref.current); return () => observer.disconnect(); }, [callback]); return ref; } Attach the returned ref to a sentinel element at the bottom of the list.