Infinite Loading(인피니트 로딩)
리액트에서 list 가 엄청 긴 컴포넌트를 렌더링 할 때 퍼포먼스 이슈가 생긴다. 그럴땐 어떻게 해결을 해야할까?
일단 가장 중요한 것은 Render Tree 를 작게 가져가는 것이다. 화면에 그려진 Element가 많이 없으면 브라우저는 렌더링 할 것이 많이 없으니 퍼포먼스를 잘 유지할 수 있다.
Render Tree는 어떻게 작게 가져가야 할까? 보통 아래와 같은 2가지 방법을 쓴다.
- Windowing: 수많은 Element를 가진 리스트에서 유저의 스크롤이 위치한 곳들의 Element만 보여주는 방법
- Infinite Loading: 리스트를 처음에 작게 가져와서(보통 서버에서 들고옴) 유저가 스크롤 함에 따라 서버에서 더 받아오는 방식
이 글에서는 Infinite Loading 을 바닐라로 한 번 구현해봐야겠다.
import { useState, useEffect, useRef, useCallback } from "react";
const ALL_ITEMS = Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`);
const ITEMS_PER_PAGE = 20;
function App() {
const [visibleCount, setVisibleCount] = useState(ITEMS_PER_PAGE);
const [loading, setLoading] = useState(false);
const targetRef = useRef<HTMLDivElement | null>(null);
const scrollContainerRef = useRef<HTMLDivElement | null>(null);
const hasMore = visibleCount < ALL_ITEMS.length;
const loadMore = useCallback(async () => {
if (!hasMore || loading) return;
setLoading(true);
// 네트워크 딜레이 효과
await new Promise((resolve) => setTimeout(resolve, 500));
setVisibleCount((prev) =>
Math.min(prev + ITEMS_PER_PAGE, ALL_ITEMS.length),
);
setLoading(false);
}, [hasMore, loading]);
useEffect(() => {
const targetElement = targetRef.current;
const scrollContainer = scrollContainerRef.current;
if (!targetElement || !scrollContainer) return;
const observer = new IntersectionObserver(
(entries) => {
const [entry] = entries;
if (entry.isIntersecting) {
loadMore();
}
},
{
root: scrollContainer,
rootMargin: "0px",
threshold: 0,
},
);
observer.observe(targetElement);
return () => observer.disconnect();
}, [loadMore]);
return (
<div className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 p-8">
<div className="max-w-2xl mx-auto">
<h1 className="text-4xl font-bold text-white mb-2 text-center">
Infinite Scroll Demo
</h1>
<p className="text-slate-400 text-center mb-8">
Showing {visibleCount} of {ALL_ITEMS.length} items
</p>
<div ref={scrollContainerRef} className="h-125 overflow-y-scroll">
<div className="space-y-3">
{ALL_ITEMS.slice(0, visibleCount).map((item, index) => (
<div
key={index}
className="bg-white/10 backdrop-blur-sm rounded-lg p-4 text-white hover:bg-white/20 transition-colors"
>
{item}
</div>
))}
<div
ref={targetRef}
className="h-20 flex items-center justify-center bg-amber-300"
>
{loading ? (
<div className="flex items-center gap-2 text-white">
<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
Loading...
</div>
) : hasMore ? (
<span className="text-white">Scroll for more...</span>
) : (
<span className="text-slate-500">End of list</span>
)}
</div>
</div>
</div>
</div>
</div>
);
}
export default App;
기본적으로 동작방식을 이해해두면 나머지는 약간 부수적인 것 같다. Intersection Observer 인스턴스를 생성하고 생성된 인스턴스에게 Target Element 를 넘겨준다. 그리고, 이 Target Element가 화면 속에서 보여질 때 어떤 액션을 취해줘! 라고 이야기 하는 것이다.
// ... intersection observer 생성
const observer = new IntersectionObserver(
(entries) => {
const [entry] = entries;
if (entry.isIntersecting) {
loadMore();
}
},
{
// root는 targetElement의 컨테이너로 생각하면 됨.
// 여기서는 targetElement가 있는 scrollContainer로 해주었다
root: scrollContainer,
// rootMargin은 컨테이너에 얼만큼 여분을 줄 것이냐로 생각하면 됨.
// 컨테이너에 여분을 0으로 잡아두면, targetElement가 보이자마자 trigger 된다 생각하면 된다.
rootMargin: "0px",
// targetElement가 얼만큼 보일때 trigger 할 것인지. 0으로 잡아주면 바로 됨
threshold: 0,
},
);
// targetElement observe 시작!
observer.observe(targetElement);
여기서 entry 는 targetElement 와 observer 가 어떻게 교차되고 있는지 상황을 나타내주는 파라미터이다. 이 파라미터가 가지는 다양한 프로퍼티들이 있는데 isIntersecting 이 실제로 target과 intersection observer에 지정해준 컨테이너가 교차하고 있는지 알려주는 boolean 값이다.
참고로 IntersectionObserver에 넘겨주는 콜백은 observer.observe(targetElemnt)가 호출될 때 한 번, 그리고 targetElement가 실제 뷰안에 들어올 때 한 번 이렇게 2가지 상황에 의해서 호출이 된다.
한계
- infinite loading으로 엄청 많이 불러왔을때 react 에서 상태변경을 하면 렉이 엄청 걸림
- cmd + f 로 검색이 안되는 이슈가 있음
참조
- Intersection Observer API - MDN: 기본적인 Intersection Observer API 의 개념과 사용 될만한 예시들을 알려줌
- Supercharge the Way You Render Large Lists in React - Uber Blog: Infinite Scroll, Windowing 을 통해서 rendering 하는 element 를 작게 가져가는 솔루션들을 설명