react-window vs react-virtualized vs react-list vs react-tiny-virtual-list vs react-infinite
虛擬滾動和無限滾動
react-windowreact-virtualizedreact-listreact-tiny-virtual-listreact-infinite類似套件:

虛擬滾動和無限滾動

虛擬滾動和無限滾動是用於處理大量數據的技術,特別是在網頁應用中。這些技術通過僅渲染可見部分的內容來提高性能,從而減少對DOM的操作和內存使用。虛擬滾動(Virtual Scrolling)是指僅渲染可見區域的元素,隨著滾動動態加載其他元素。無限滾動(Infinite Scrolling)則是在用戶滾動到頁面底部時自動加載更多內容。這些技術特別適合用於長列表、圖像畫廊和社交媒體應用。

npm下載趨勢

3 年

GitHub Stars 排名

統計詳情

套件
下載數
Stars
大小
Issues
發布時間
許可
react-window8,481,69417,212428 kB15 天前MIT
react-virtualized2,262,03727,0671.31 MB119 天前MIT
react-list651,5131,97035.3 kB724 個月前MIT
react-tiny-virtual-list140,3272,483-558 年前MIT
react-infinite10,1032,682243 kB101-BSD-3-Clause

功能比較: react-window vs react-virtualized vs react-list vs react-tiny-virtual-list vs react-infinite

虛擬化 vs 無限滾動

  • react-window:

    react-window 提供輕量級的虛擬化解決方案,支持列表和網格。它不直接支持無限滾動,但可以與其他組件結合使用。

  • react-virtualized:

    react-virtualized 提供全面的虛擬化解決方案,包括列表、網格和無限滾動。它功能強大,但配置較為複雜。

  • react-list:

    react-list 支持虛擬化和無限滾動,允許開發者根據需要選擇。它的靈活性使其適合各種場景,但需要手動實現無限滾動邏輯。

  • react-tiny-virtual-list:

    react-tiny-virtual-list 專注於虛擬化,僅渲染可見區域的元素。它不支持無限滾動,但在處理大型數據集時性能優越。

  • react-infinite:

    react-infinite 專注於無限滾動,通過監控滾動位置自動加載更多內容。它不提供虛擬化功能,因此在處理大量數據時可能會影響性能。

性能

  • react-window:

    react-window 提供優秀的性能,特別是在渲染大量列表項目時。它的輕量級設計使其在性能和資源使用方面表現出色。

  • react-virtualized:

    react-virtualized 性能強大,但在處理極大數據集時可能會遇到瓶頸。它提供了多種優化選項,但需要適當配置。

  • react-list:

    react-list 性能良好,特別是在啟用虛擬化時。它能有效地處理大型數據集,但無限滾動的性能取決於數據加載的實現。

  • react-tiny-virtual-list:

    react-tiny-virtual-list 在處理大型數據集時性能最佳,因為它僅渲染可見元素。這大大減少了DOM操作和內存使用。

  • react-infinite:

    react-infinite 在處理大量數據時性能可能下降,因為它不進行虛擬化。隨著列表項目數量的增加,渲染時間和內存使用會增加。

包大小

  • react-window:

    react-window 相對較小,提供虛擬化功能而不會顯著增加包大小。這使它成為需要虛擬化但又不想增加太多負擔的項目的理想選擇。

  • react-virtualized:

    react-virtualized 包含大量功能,導致其大小較大。對於需要全面虛擬化解決方案的項目來說,這是一個合理的權衡。

  • react-list:

    react-list 包大小較小,適合對性能敏感的應用。

  • react-tiny-virtual-list:

    react-tiny-virtual-list 是這些庫中最小的,對於需要減少加載時間和帶寬使用的項目非常合適。

  • react-infinite:

    react-infinite 包大小適中,對於需要快速集成的項目來說是個不錯的選擇。

易用性

  • react-window:

    react-window 提供簡單的虛擬化 API,易於使用。對於需要快速實現虛擬化的開發者來說非常直觀。

  • react-virtualized:

    react-virtualized 功能強大,但學習曲線較陡。需要花時間來理解其各種組件和配置選項。

  • react-list:

    react-list 提供靈活的 API,但對於新手來說可能需要一些時間來熟悉。

  • react-tiny-virtual-list:

    react-tiny-virtual-list API 簡潔,易於理解。對於需要虛擬化但不需要複雜配置的開發者來說非常友好。

  • react-infinite:

    react-infinite API 簡單易用,特別是對於無限滾動。文檔清晰,適合快速實現。

代碼示例

  • react-window:

    虛擬化列表示例

    import React from 'react';
    import { FixedSizeList } from 'react-window';
    
    const items = Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`);
    
    const WindowedList = () => {
      return (
        <FixedSizeList
          height={300}
          itemCount={items.length}
          itemSize={35}
          width={300}
        >
          {({ index, style }) => (
            <div style={style}>{items[index]}</div>
          )}
        </FixedSizeList>
      );
    };
    
    export default WindowedList;
    
  • react-virtualized:

    虛擬化列表示例

    import React from 'react';
    import { List } from 'react-virtualized';
    
    const VirtualizedList = () => {
      const items = Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`);
    
      return (
        <List
          height={300}
          rowCount={items.length}
          rowHeight={30}
          rowRenderer={({ index, key, style }) => (
            <div key={key} style={style}>
              {items[index]}
            </div>
          )}
          width={300}
        />
      );
    };
    
    export default VirtualizedList;
    
  • react-list:

    虛擬化列表示例

    import React from 'react';
    import { List } from 'react-list';
    
    const VirtualizedList = () => {
      const items = Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`);
    
      return (
        <List
          itemRenderer={(index, key) => (
            <div key={key} style={{ height: 30 }}>
              {items[index]}
            </div>
          )}
          length={items.length}
          type='uniform'
        />
      );
    };
    
    export default VirtualizedList;
    
  • react-tiny-virtual-list:

    虛擬化列表示例

    import React from 'react';
    import { VariableSizeList } from 'react-tiny-virtual-list';
    
    const getItemSize = (index) => 35; // 每個項目的高度
    
    const TinyVirtualList = () => {
      const items = Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`);
    
      return (
        <VariableSizeList
          height={300}
          itemCount={items.length}
          itemSize={getItemSize}
          width={300}
        >
          {({ index, style }) => (
            <div style={style}>{items[index]}</div>
          )}
        </VariableSizeList>
      );
    };
    
    export default TinyVirtualList;
    
  • react-infinite:

    無限滾動示例

    import React from 'react';
    import Infinite from 'react-infinite';
    
    const InfiniteList = () => {
      const items = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`);
    
      return (
        <Infinite
          containerHeight={300}
          elementHeight={50}
          infiniteLoadBeginEdgeOffset={200}
          onInfiniteLoad={() => console.log('Load more items')}
          isInfiniteLoading={false}
        >
          {items.map((item) => (
            <div key={item} style={{ height: 50 }}>
              {item}
            </div>
          ))}
        </Infinite>
      );
    };
    
    export default InfiniteList;
    

如何選擇: react-window vs react-virtualized vs react-list vs react-tiny-virtual-list vs react-infinite

  • react-window:

    選擇 react-window 如果您需要一個輕量級的虛擬化解決方案,類似於 react-virtualized 但更簡潔。它適合需要基本虛擬化功能的項目,並且對性能和包大小有良好的平衡。

  • react-virtualized:

    選擇 react-virtualized 如果您需要一個功能全面的虛擬化庫,支持各種列表和網格布局。它提供了豐富的功能和配置選項,但學習曲線較陡,適合需要高度自定義的應用。

  • react-list:

    選擇 react-list 如果您需要一個輕量級的列表組件,支持虛擬滾動和無限滾動。它提供了靈活的API,適合需要自定義渲染邏染的項目。

  • react-tiny-virtual-list:

    選擇 react-tiny-virtual-list 如果您需要一個小巧且高效的虛擬滾動組件,特別是對於大型數據集。它的設計簡單,性能優越,適合對包大小敏感的項目。

  • react-infinite:

    選擇 react-infinite 如果您需要一個簡單的無限滾動解決方案,並且不介意手動處理加載更多數據的邏輯。它適合小型項目或需要快速實現無限滾動的應用。

react-window 的 README

react-window logo

react-window is a component library that helps render large lists of data quickly and without the performance problems that often go along with rendering a lot of data. It's used in a lot of places, from React DevTools to the Replay browser.

Support

If you like this project there are several ways to support it:

The following wonderful companies and individuals have sponsored react-window:

Installation

Begin by installing the library from NPM:

npm install react-window

TypeScript types

TypeScript definitions are included within the published dist folder

FAQs

Frequently asked questions can be found here.

Documentation

Documentation for this project is available at react-window.vercel.app.

List

Renders data with many rows.

Required props

NameDescription
rowComponent

React component responsible for rendering a row.

This component will receive an index and style prop by default. Additionally it will receive prop values passed to rowProps.

ℹ️ Spread ariaAttributes onto the row element; they identify it as a row (e.g. so that dynamic row heights are measured reliably)

ℹ️ The prop types for this component are exported as RowComponentProps

rowCount

Number of items to be rendered in the list.

rowHeight

Row height; the following formats are supported:

  • number of pixels (number)
  • percentage of the list's current height (string)
  • function that returns the row height (in pixels) given an index and rowProps
  • dynamic row height cache returned by the useDynamicRowHeight hook

ℹ️ Percentage heights can't be resolved during server rendering unless a defaultHeight (or a pixel height via the style prop) is specified.

⚠️ Dynamic row heights are not as efficient as predetermined sizes. It's recommended to provide your own height values if they can be determined ahead of time.

rowProps

Additional props to be passed to the row-rendering component. List will automatically re-render rows when values in this object change.

⚠️ This object must not contain ariaAttributes, index, or style props.

Optional props

NameDescription
className

CSS class name.

style

Optional CSS properties. The list of rows will fill the height defined by this style.

children

Additional content to be rendered within the list (above rows). This property can be used to render things like overlays or tooltips.

defaultHeight

Default height of list (in pixels) for initial render, before its actual height has been measured.

ℹ️ Lists can't be measured during server rendering, so this value determines how many rows are server rendered. It's recommended to set this to the expected height of the list (or to specify a pixel height via the style prop).

defaultScrollOffset

Initial scroll offset (in pixels) of the list. This value is only applied once, when the list first mounts with at least one row.

ℹ️ Server-rendered HTML can't be pre-scrolled, so server rendering always starts at the first row; the default scroll offset is applied once the list hydrates.

⚠️ If the list can't be scrolled that far when the offset is applied (e.g. it is hidden with display: none, or uses percentage row heights before its height has been measured), the offset is clamped or ignored and not retried. Specify a defaultHeight (or a pixel height via the style prop) when using percentage row heights.

listRef

Ref used to interact with this component's imperative API.

This API has imperative methods for scrolling and a getter for the outermost DOM element.

ℹ️ The useListRef and useListCallbackRef hooks are exported for convenience in TypeScript projects.

onResize

Callback notified when the List's outermost HTMLElement resizes. This may be used to (re)scroll a row into view.

onRowsRendered

Callback notified when the range of visible rows changes.

overscanCount

How many additional rows to render outside of the visible area. This can reduce visual flickering near the edges of a list when scrolling.

rowKey

Lists use the row index as a key by default. This prop can provide a custom key value.

ℹ️ Custom keys can ensure better UX for sortable or filterable lists, particularly if your row components are stateful. Refer to the React documentation for more info.

⚠️ This prop cannot be auto-memoized because it is called during render. It is important to always useCallback for this prop; do not use an inline function.

scrollElement

Element that scrolls the list, for lists that scroll along with other content (e.g. the page):

  • "window" to scroll with the page
  • an ancestor element that scrolls (e.g. stored with a useState ref callback); null until it has mounted

The list renders at its full height and only renders the rows visible within the scroll element's viewport. Its position within the scroll element is measured whenever it renders, scrolls, or resizes, and whenever content before it is resized, inserted, or removed (e.g. an image loading above the list).

  • scrollToRow scrolls the scroll element
  • defaultHeight is used as the viewport height until the scroll element has been measured (e.g. during server rendering)
  • percentage row heights are relative to the scroll element's viewport height
  • defaultScrollOffset is ignored

ℹ️ While the scroll element is null, the list renders the first rows (as it does during server rendering).

⚠️ The list itself doesn't scroll, so its onScroll handler isn't called; listen to the scroll element's "scroll" events instead (or use the useIsScrolling hook).

tagName

Can be used to override the root HTML element rendered by the List component. The default value is "div", meaning that List renders an HTMLDivElement as its root.

⚠️ In most use cases the default ARIA roles are sufficient and this prop is not needed.

Grid

Renders data with many rows and columns.

ℹ️ Unlike List rows, Grid cell sizes must be known ahead of time. Either static sizes or something that can be derived (from the data in CellProps) without rendering.

Required props

NameDescription
cellComponent

React component responsible for rendering a cell.

This component will receive columnIndex, rowIndex, and style props by default. Additionally it will receive prop values passed to cellProps.

ℹ️ The prop types for this component are exported as CellComponentProps

cellProps

Additional props to be passed to the cell-rendering component. Grid will automatically re-render cells when values in this object change.

⚠️ This object must not contain ariaAttributes, columnIndex, rowIndex, or style props.

columnCount

Number of columns to be rendered in the grid.

columnWidth

Column width; the following formats are supported:

  • number of pixels (number)
  • percentage of the grid's current width (string)
  • function that returns the column width (in pixels) given an index and cellProps

ℹ️ Percentage widths can't be resolved during server rendering unless a defaultWidth (or a pixel width via the style prop) is specified.

rowCount

Number of rows to be rendered in the grid.

rowHeight

Row height; the following formats are supported:

  • number of pixels (number)
  • percentage of the grid's current height (string)
  • function that returns the row height (in pixels) given an index and cellProps

ℹ️ Percentage heights can't be resolved during server rendering unless a defaultHeight (or a pixel height via the style prop) is specified.

Optional props

NameDescription
className

CSS class name.

dir

Indicates the directionality of grid cells.

ℹ️ The directionality of an ancestor element can't be detected during server rendering; specify this prop explicitly for server-rendered right-to-left grids.

ℹ️ See HTML dir global attribute for more information.

style

Optional CSS properties. The grid of cells will fill the height and width defined by this style.

children

Additional content to be rendered within the grid (above cells). This property can be used to render things like overlays or tooltips.

columnKey

Grids use the column index as a key by default. This prop can be used along with the rowKey prop to provide a custom key value.

ℹ️ Custom keys can ensure better UX for sortable or filterable grids, particularly if your cell components are stateful. Refer to the React documentation for more info.

⚠️ This prop cannot be auto-memoized because it is called during render. It is important to always useCallback for this prop; do not use an inline function.

defaultHeight

Default height of grid (in pixels) for initial render, before its actual height has been measured.

ℹ️ Grids can't be measured during server rendering, so this value determines how many rows are server rendered. It's recommended to set this to the expected height of the grid (or to specify a pixel height via the style prop).

defaultScrollLeft

Initial horizontal scroll offset (in pixels) of the grid. This value is only applied once, when the grid first mounts with at least one column.

ℹ️ Server-rendered HTML can't be pre-scrolled, so server rendering always starts at the first column; the default scroll offset is applied once the grid hydrates.

⚠️ If the grid can't be scrolled that far when the offset is applied (e.g. it is hidden with display: none, or uses percentage column widths before its width has been measured), the offset is clamped or ignored and not retried. Specify a defaultWidth (or a pixel width via the style prop) when using percentage column widths.

defaultScrollTop

Initial vertical scroll offset (in pixels) of the grid. This value is only applied once, when the grid first mounts with at least one row.

ℹ️ Server-rendered HTML can't be pre-scrolled, so server rendering always starts at the first row; the default scroll offset is applied once the grid hydrates.

⚠️ If the grid can't be scrolled that far when the offset is applied (e.g. it is hidden with display: none, or uses percentage row heights before its height has been measured), the offset is clamped or ignored and not retried. Specify a defaultHeight (or a pixel height via the style prop) when using percentage row heights.

defaultWidth

Default width of grid (in pixels) for initial render, before its actual width has been measured.

ℹ️ Grids can't be measured during server rendering, so this value determines how many columns are server rendered. It's recommended to set this to the expected width of the grid (or to specify a pixel width via the style prop).

gridRef

Imperative Grid API.

ℹ️ The useGridRef and useGridCallbackRef hooks are exported for convenience in TypeScript projects.

onCellsRendered

Callback notified when the range of rendered cells changes.

onResize

Callback notified when the Grid's outermost HTMLElement resizes. This may be used to (re)scroll a cell into view.

overscanCount

How many additional rows/columns to render outside of the visible area. This can reduce visual flickering near the edges of a grid when scrolling.

rowKey

Grids use the row index as a key by default. This prop can be used along with the columnKey prop to provide a custom key value.

ℹ️ Custom keys can ensure better UX for sortable or filterable grids, particularly if your cell components are stateful. Refer to the React documentation for more info.

⚠️ This prop cannot be auto-memoized because it is called during render. It is important to always useCallback for this prop; do not use an inline function.

scrollElement

Element that scrolls the grid, for grids that scroll along with other content (e.g. the page):

  • "window" to scroll with the page
  • an ancestor element that scrolls (e.g. stored with a useState ref callback); null until it has mounted

The grid renders at its full height and only renders the rows (and columns) visible within the scroll element's viewport. Its position within the scroll element is measured whenever it renders, scrolls, or resizes, and whenever content before it is resized, inserted, or removed (e.g. an image loading above the grid).

  • columns scroll with the scroll element too if the grid is as wide as its content (e.g. style={{ width: "max-content" }}); otherwise the grid fills the width of its parent and its columns scroll within it
  • scrollToCell, scrollToColumn and scrollToRow scroll whichever element scrolls each axis
  • defaultHeight and defaultWidth are used as the viewport size until the scroll element has been measured (e.g. during server rendering)
  • percentage row heights and column widths are relative to the scroll element's viewport
  • defaultScrollLeft and defaultScrollTop are ignored

ℹ️ While the scroll element is null, the grid renders the first rows (as it does during server rendering).

⚠️ The grid's onScroll handler is only called when the grid scrolls its own columns; listen to the scroll element's "scroll" events instead (or use the useIsScrolling hook).

tagName

Can be used to override the root HTML element rendered by the Grid component. The default value is "div", meaning that Grid renders an HTMLDivElement as its root.

⚠️ In most use cases the default ARIA roles are sufficient and this prop is not needed.