Skip to Content
ohooks

useVirtualList

Virtualizes a large list of fixed or variable-height items so only visible rows are rendered.

Loading preview...

The useVirtualList hook virtualizes large lists of fixed or variable-height items by observing scroll position and container height, rendering only the visible slice (plus configurable overscan rows) and providing a scrollToIndex helper.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useVirtualList.json

Usage

Examples

Fixed-Height Virtualized List (10,000 Rows)

Spread wrapperProps onto an inner wrapper element and position each virtual item at offsetTop.

Variable-Height Rows

Pass a function (index, item) => number as itemHeight to compute dynamic row heights using binary search.

API Reference

UseVirtualListOptions

Configuration options for scroll container target, row height calculation, and overscan count.

Property
Specification
containerTargetrequired
EventListenerTarget<object>
Ref, element, or getter for the scrollable container element.
itemHeightrequired
union
Fixed pixel height or function returning the pixel height for each item index.
overscan?
numberdefault:5
Number of extra items to render above and below the visible viewport

VirtualItem

Metadata and positioning descriptor for each visible virtualized row.

Property
Specification
indexrequired
number
Index of the item in the source items array.
datarequired
T
The item data at index.
offsetToprequired
number
Top offset in pixels from the start of the scrollable content.
heightrequired
number
Computed height of the item in pixels.

UseVirtualListReturn

Visible virtual items, total height, wrapper props, and scrollToIndex helper returned by the hook.

Property
Specification
virtualItems
array
Slice of items currently within the visible viewport plus overscan.
totalHeight
number
Total pixel height of all items combined.
wrapperProps
object
Style props to spread onto the inner positioning wrapper element.
scrollToIndex
function
Scrolls the container to bring the item at index into view.