How to Implement Virtual Scrolling: Claude Code 활용 가이드
implement virtual scrolling: Claude Code 활용. 실용적인 코드 예시와 단계별 가이드를 포함합니다.
仮想스크롤が必要な場面
数千〜数万件の리스트を표시する際、모든DOM要素を描画すると브라우저の성능が大幅に低下します。仮想스크롤(ウィンドウイング)は、画面に見えている部分だけをDOMに描画する手法です。Claude Code를 활용하면 이高度な최적화技術を효율적으로구현할 수 있습니다。
기본적인仮想스크롤の구현
> 固定高さアイテムの仮想스크롤컴포넌트を作って。
> 10万件の리스트でもスムーズに動くようにして。
import { useState, useRef, useCallback, useMemo } from 'react';
interface VirtualListProps<T> {
items: T[];
itemHeight: number;
containerHeight: number;
overscan?: number;
renderItem: (item: T, index: number) => React.ReactNode;
}
function VirtualList<T>({
items, itemHeight, containerHeight, overscan = 5, renderItem,
}: VirtualListProps<T>) {
const [scrollTop, setScrollTop] = useState(0);
const containerRef = useRef<HTMLDivElement>(null);
const totalHeight = items.length * itemHeight;
const visibleCount = Math.ceil(containerHeight / itemHeight);
const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - overscan);
const endIndex = Math.min(items.length, startIndex + visibleCount + overscan * 2);
const visibleItems = useMemo(
() => items.slice(startIndex, endIndex),
[items, startIndex, endIndex]
);
const handleScroll = useCallback(() => {
if (containerRef.current) {
setScrollTop(containerRef.current.scrollTop);
}
}, []);
return (
<div
ref={containerRef}
onScroll={handleScroll}
style={{ height: containerHeight, overflow: 'auto' }}
role="list"
aria-label={`リスト(全${items.length}件)`}
>
<div style={{ height: totalHeight, position: 'relative' }}>
{visibleItems.map((item, i) => {
const index = startIndex + i;
return (
<div
key={index}
role="listitem"
style={{
position: 'absolute',
top: index * itemHeight,
height: itemHeight,
width: '100%',
}}
>
{renderItem(item, index)}
</div>
);
})}
</div>
</div>
);
}
可変高さアイテムへの대응
> アイテムごとに高さが異なる仮想스크롤にも대응して。
class DynamicSizeManager {
private heights: Map<number, number> = new Map();
private estimatedHeight: number;
constructor(estimatedHeight: number) {
this.estimatedHeight = estimatedHeight;
}
setHeight(index: number, height: number) {
this.heights.set(index, height);
}
getHeight(index: number): number {
return this.heights.get(index) ?? this.estimatedHeight;
}
getOffset(index: number): number {
let offset = 0;
for (let i = 0; i < index; i++) {
offset += this.getHeight(i);
}
return offset;
}
getTotalHeight(itemCount: number): number {
return this.getOffset(itemCount);
}
findIndexAtOffset(offset: number, itemCount: number): number {
let current = 0;
for (let i = 0; i < itemCount; i++) {
current += this.getHeight(i);
if (current > offset) return i;
}
return itemCount - 1;
}
}
高さ自動計測컴포넌트
import { useRef, useEffect } from 'react';
function MeasuredItem({ index, onMeasure, children }: {
index: number;
onMeasure: (index: number, height: number) => void;
children: React.ReactNode;
}) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (ref.current) {
const observer = new ResizeObserver(([entry]) => {
onMeasure(index, entry.contentRect.height);
});
observer.observe(ref.current);
return () => observer.disconnect();
}
}, [index, onMeasure]);
return <div ref={ref}>{children}</div>;
}
TanStack Virtualの활용
より本格的な구현にはTanStack Virtualが便利です。
import { useVirtualizer } from '@tanstack/react-virtual';
function VirtualizedList({ items }: { items: string[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 50,
overscan: 10,
});
return (
<div ref={parentRef} style={{ height: 600, overflow: 'auto' }}>
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
{virtualizer.getVirtualItems().map((virtualItem) => (
<div
key={virtualItem.key}
style={{
position: 'absolute',
top: 0,
transform: `translateY(${virtualItem.start}px)`,
width: '100%',
}}
>
{items[virtualItem.index]}
</div>
))}
</div>
</div>
);
}
정리
Claude Code를 활용하면 固定高さ・可変高さの仮想스크롤から、TanStack Virtualの활용まで효율적으로구현할 수 있습니다。無限스크롤との組み合わせは無限스크롤구현を、全般的な성능改善は성능최적화를 참고하세요.
TanStack Virtual의 상세 정보는TanStack Virtual공식 문서를 확인하세요.
무료 PDF: 5분 완성 Claude Code 치트시트
이메일 주소만 등록하시면 A4 한 장짜리 치트시트 PDF를 즉시 보내드립니다.
개인정보는 엄격하게 관리하며 스팸은 보내지 않습니다.
이 글을 작성한 사람
Masa
Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.
관련 글
Claude Code용 CLAUDE.md 템플릿 7선 | 실제 프로젝트에 바로 붙여 넣는 예시
개인 앱, 콘텐츠 사이트, API, 팀 저장소, 레거시 코드베이스에 맞는 실전 CLAUDE.md 템플릿 7개와 피해야 할 실패 사례를 정리했습니다.
Claude Code Approval / Sandbox Guide | 매일 안전하게 쓰는 설정법
Claude Code의 allow, ask, deny, sandbox를 어떻게 나눌지, 실전 settings와 hooks, 실패 사례와 함께 정리합니다.
Claude Code 완벽 입문 가이드 2026 | 제로부터 실무 활용까지 7단계
Claude Code를 처음 사용하는 분들을 위한 완전 입문 가이드. 설치부터 실제 개발 워크플로우에 녹이는 것까지 — Masa가 처음에 겪었던 모든 시행착오를 바탕으로 정리했습니다.