shadcn-ahooks

useVirtualList

A hook that allows you to use virtual list to render huge chunks of list data.

Overview

A hook that allows you to use virtual list to render huge chunks of list data.

Documentation and Examples

Installation

Open in
pnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useVirtualList.json
npx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useVirtualList.json
yarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useVirtualList.json
bun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useVirtualList.json

A hook that allows you to use virtual list to render huge chunks of list data.

Examples

Default usage

Dynamic item height

API

const [list, scrollTo] = useVirtualList<T>(
  originalList: T[],
  options: {
    containerTarget: (() => Element) | Element | MutableRefObject<Element>,
    wrapperTarget: (() => Element) | Element | MutableRefObject<Element>,
    itemHeight: number | ((index: number, data: T) => number),
    overscan?: number,
  }
);

Params

PropertyDescriptionTypeDefault
originalListThe original list that contains a lot of data entries. Attention: must undergo useMemo processing or never change, otherwise there will be a dead loopT[][]
optionsconfigOptions-

Options

PropertyDescriptionTypeDefault
containerTargetOutter Container,support DOM element or ref() => Element | Element | MutableRefObject<Element>-
wrapperTargetInner Container,DOM element or ref() => Element | Element | MutableRefObject<Element>-
itemHeightItem height, accept a pixel value or a function that returns the heightnumber | ((index: number, data: T) => number)-
overscanThe extra buffer items outside of the view areanumber5

Result

PropertyDescriptionType
listThe current portion of data need to be rendered to DOM{ data: T, index: number }[]
scrollToScroll to specific index(index: number) => void

On this page