High-performance virtual list hook for React
npm install @windowing-kit/virtual-listHigh-performance virtual list hook for React. Efficiently renders large lists by only rendering visible items.
``bash`
npm install @windowing-kit/virtual-listor
pnpm add @windowing-kit/virtual-listor
yarn add @windowing-kit/virtual-list
`tsx
import { useVirtualList } from "@windowing-kit/virtual-list";
function MyList() {
const items = Array.from({ length: 10000 }, (_, i) => ({
id: i,
name: Item ${i},
}));
const { containerRef, listHeight, virtualItems } = useVirtualList({
itemHeight: 50,
items,
overscan: 3,
});
return (
API
$3
Virtual list hook.
#### Options
| Property | Type | Required | Default | Description |
| ------------ | -------- | -------- | ------- | ---------------------------------------------- |
|
itemHeight | number | Yes | - | Height of each item in pixels |
| items | T[] | Yes | - | Array of items to render |
| overscan | number | No | 3 | Number of items to render outside the viewport |#### Return
| Property | Type | Description |
| -------------- | ---------------------------------------- | -------------------------------------------------------- |
|
containerRef | (element: HTMLElement \| null) => void | Ref callback to attach to the scroll container |
| listHeight | number | Total height of the list in pixels |
| virtualItems | VirtualItem | Array of virtual items currently visible in the viewport |$3
Each virtual item has the following properties:
| Property | Type | Description |
| --------- | -------- | ---------------------------------- |
|
index | number | Index in the original array |
| offsetY | number | Y offset in pixels within the list |
| data | T | Original item data |Examples
$3
`tsx
import { useVirtualList } from "@windowing-kit/virtual-list";function TodoList({ todos }) {
const { containerRef, listHeight, virtualItems } = useVirtualList({
itemHeight: 60,
items: todos,
overscan: 5,
});
return (
{virtualItems.map((virtualItem) => (
key={virtualItem.index}
style={{
position: "absolute",
top: virtualItem.offsetY,
height: 60,
width: "100%",
padding: "10px",
borderBottom: "1px solid #eee",
}}
>
{virtualItem.data.title}
))}
$3
`tsx
function StyledList({ items }) {
const { containerRef, listHeight, virtualItems } = useVirtualList({
itemHeight: 80,
items,
}); return (
ref={containerRef}
className="scroll-container"
style={{ height: "600px", overflow: "auto" }}
>
{virtualItems.map((virtualItem) => (
key={virtualItem.index}
className="list-item"
style={{
position: "absolute",
top: virtualItem.offsetY,
height: 80,
width: "100%",
}}
>
{virtualItem.data.title}
{virtualItem.data.description}
))}