https://taejinii.tistory.com/50
FrontEnd - React-query 를 이용한 무한스크롤 구현하기 - (1)
무한스크롤 이란? 무한 스크롤은 웹사이트나 애플리케이션에서 사용되는 사용자 경험 기법 중 하나입니다. 일반적으로 긴 목록이나 콘텐츠가 있는 페이지에서 스크롤을 내리면, 새로운 콘텐츠
taejinii.tistory.com
첫번째 글을 안보신분들은 해당 글을 보고 오시면 됩니다.
첫번째 글에 이어 두번째 글에서는 데이터를 계속 불러와줄수있는 트리거를 해주는 Observer 에 대해서 설명하겠습니다.
const Observer = () => {
const [ref, inView] = useInView({ threshold: 0 });
useEffect(() => {
if (!data || !hasNextPage) return;
if (hasNextPage && inView) fetchNextPage();
}, [inView]);
// 다음페이지가 없다면 옵저버 제거
if(!hasNextpage) return;
// 다음 페이지 데이터를 불러오는동안 스켈레톤 컴포넌트 보여주기
return isFetchingNextPage ? (
<CollectionListLoading skeletonCount={12} />
) : (
<div ref={ref} />
);
};
react-intersection-observer 를 설치하면 useInView 훅을 사용할 수 있습니다.
어떠한 컴포넌트의 ref 를 연결한후 해당 컴포넌트가 뷰포트에 잡히게되면 inView 가 true로 바뀌게됩니다.
useInView 의 옵션인 threshold 는 0~1 까지 있으며 1은 ref가 연결된 컴포넌트가 완전히 화면에 보일때 inView 가 ture로 바뀌며
0으로 설정하면 해당컴포넌트가 보이는순간 inView 가 true 로 바뀌게 됩니다.
// CollectionList.tsx
"use client";
import Card from "@/components/ui/Card";
import { useGetCollectionList } from "@/hooks/queries/useGetCollectionList";
import CollectionListLoading from "@/components/ui/Skeleton/CollectionListLoading";
export default function CollectionList({
collectionName,
}: {
collectionName: string;
}) {
const { data, isLoading, Observer, isSuccess } =
useGetCollectionList(collectionName);
return (
<section className="responsive-container">
{isLoading && !isSuccess ? (
<CollectionListLoading skeletonCount={12} />
) : (
<div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6">
{data?.pages.map((nft) => {
return (
<Card
key={nft.identifier}
identifier={nft.identifier}
contract={nft.contract}
image_url={nft.image_url}
name={nft.name}
collection={nft.collection}
/>
);
})}
</div>
)}
<Observer />
</section>
);
}
실제 제가 사용한 CollectionList 컴포넌트 입니다.
여기에서도 처음 페이지에 접속하여 로딩중일때 CollectionList 컴포넌트는 스켈레톤 컴포넌트를 처음 보여주게됩니다.
그후 Observer 컴포넌트가 뷰포트에 잡히면 무한스크롤이 트리거되어 다음 데이터를 불러오게 되는구조입니다.
'FrontEnd' 카테고리의 다른 글
FrontEnd - Tailwindcss 동적 스타일링 하기 (0) | 2023.07.27 |
---|---|
FrontEnd - 재사용성 높인 버튼 공통컴포넌트 만들어보기 with.tailwindcss (0) | 2023.07.09 |
FrontEnd - React-query 를 이용한 무한스크롤 구현하기 - (1) (0) | 2023.07.06 |
Frontend - 프론트엔드 웹 성능 최적화 도전기 with Next.js (0) | 2023.07.03 |
Frontent - SSR(ServerSideRendering) vs CSR(ClientSideRendering) (0) | 2023.06.29 |