import { useEffect, useRef, useState } from "react";
function useInvertedInfiniteScroll(
fetchNextPage: () => Promise<unknown>,
hasNextPage: boolean = false,
dataLength: number = 0
) {
const containerRef = useRef<HTMLDivElement>(null);
const [prevScrollHeight, setPrevScrollHeight] = useState(0);
useEffect(function scrollToPrevScrollHeight() {
// 만약 prevScrollHeight가 0이라면 === 첫 페이지라면
if (prevScrollHeight === 0) {
// 맨 아래로 스크롤을 내립니다.
containerRef.current?.scrollTo({
top: containerRef.current.scrollHeight,
})
return;
}
// 아닐 경우, 스크롤의 높이를 변경합니다.
containerRef.current?.scrollTo({
top: containerRef.current.scrollHeight - prevScrollHeight,
});
}, [prevScrollHeight, dataLength])
// 스크롤 이벤트 핸들러
function handleScroll() {
// 만약 다음 페이지가 없다면
if (!hasNextPage) {
// 코드를 실행하지 않습니다.
return;
}
// 이전 스크롤 높이에서 현재 scrollTop를 뺸 높이를 기억하고
setPrevScrollHeight((containerRef.current?.scrollHeight ?? 0) - (containerRef.current?.scrollTop ?? 0));
// 만약 스크롤이 450px 미만으로 줄어들었다면
if ((containerRef.current?.scrollTop ?? 0) < 450) {
// 다음 페이지를 가져옵니다.
fetchNextPage();
}
}
return {
containerRef,
handleScroll,
};
}
TypeScript
복사