@bongsik/virtual-list
v0.1.2
Published
React hook for virtualized list rendering
Maintainers
Readme
@bongsik/virtual-list
React hook for virtualized list rendering to improve performance with large lists.
Installation
npm install @bongsik/virtual-list
# or
pnpm add @bongsik/virtual-list
# or
yarn add @bongsik/virtual-listUsage
import { useVirtualList } from "@bongsik/virtual-list";
function MyList() {
const items = Array.from({ length: 10000 }, (_, i) => `Item ${i}`);
const {
virtualItems,
totalHeight,
containerStyle,
handleScroll,
scrollElementRef,
} = useVirtualList({
itemCount: items.length,
itemHeight: 50, // 고정 높이
containerHeight: 400,
overscan: 3,
});
return (
<div ref={scrollElementRef} style={containerStyle} onScroll={handleScroll}>
<div style={{ height: totalHeight, position: "relative" }}>
{virtualItems.map((virtualItem) => (
<div
key={virtualItem.index}
style={{
position: "absolute",
top: virtualItem.start,
height: virtualItem.size,
width: "100%",
}}
>
{items[virtualItem.index]}
</div>
))}
</div>
</div>
);
}동적 높이 사용
const {
virtualItems,
totalHeight,
containerStyle,
handleScroll,
scrollElementRef,
} = useVirtualList({
itemCount: items.length,
itemHeight: (index) => {
// 각 아이템의 높이를 동적으로 계산
return index % 2 === 0 ? 50 : 80;
},
containerHeight: 400,
});
return (
<div ref={scrollElementRef} style={containerStyle} onScroll={handleScroll}>
{/* ... */}
</div>
);API
useVirtualList(options)
Options
| Property | Type | Default | Description |
| ----------------- | --------------------------------------- | ------------- | ----------------------------------------------------------------------------------- |
| itemCount | number | required | 전체 아이템 개수 |
| itemHeight | number \| ((index: number) => number) | required | 각 아이템의 높이 (px) 또는 높이 계산 함수 |
| containerHeight | number | 0 | 컨테이너 높이. containerRef나 scrollElementRef를 사용하는 경우 선택 |
| containerRef | RefObject<HTMLElement> | undefined | 이미 존재하는 컨테이너 요소를 전달할 때 사용 |
| overscan | number | 3 | 화면 밖에 렌더링할 추가 아이템 개수 |
| scrollOffset | number | 0 | 초기 스크롤 오프셋 (px) 또는 외부 제어 값 |
| scrollTarget | "container" \| "window" | "container" | 스크롤을 감지할 대상. window 모드에서는 handleScroll/containerStyle이 필요 없음 |
Returns
| Property | Type | Description |
| ------------------ | ------------------------------------------------------ | -------------------------------------------------------------- |
| virtualItems | VirtualItem[] | 현재 보이는 가상 아이템들 |
| totalHeight | number | 전체 리스트의 총 높이 (px) |
| containerStyle | React.CSSProperties | 컨테이너에 적용할 스타일 (scrollTarget === "container"일 때) |
| handleScroll | (e: React.UIEvent<HTMLElement>) => void \| undefined | 스크롤 이벤트 핸들러. 컨테이너 모드에서만 제공 |
| scrollElementRef | RefObject<HTMLDivElement> | 컨테이너 ref가 없다면 이 ref를 컨테이너에 연결 |
VirtualItem
| Property | Type | Description |
| -------- | -------- | ----------------------- |
| index | number | 아이템의 인덱스 |
| start | number | 아이템의 시작 위치 (px) |
| size | number | 아이템의 크기 (px) |
| end | number | 아이템의 끝 위치 (px) |
License
MIT
