8000 GitHub - ersinkoc/Scrollex: Zero-dependency React virtualization library with micro-kernel plugin architecture · GitHub
[go: up one dir, main page]

Skip to content
ersinkocPublic

About

Zero-dependency React virtualization library with micro-kernel plugin architecture

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

62 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Scrollex

Zero-dependency React virtualization library with micro-kernel plugin architecture

npm version bundle size license TypeScript

Documentation | Examples | GitHub


Features

  • Zero Dependencies - No runtime dependencies, React is a peer dependency
  • High Performance - Renders only the visible rows of 100k+ item lists, with RAF-throttled scroll handling
  • Micro-Kernel Architecture - Plugin-based kernel, ~12KB min+gzip for the core (see Bundle size)
  • Variable Heights - Auto-measurement for dynamic content
  • Infinite Scroll - Built-in bidirectional infinite loading
  • Multiple Layouts - List, Grid, and Masonry components
  • TypeScript First - Full type safety with strict mode
  • Accessible - Keyboard navigation and ARIA support

Installation

npm install @oxog/scrollex
yarn add @oxog/scrollex
pnpm add @oxog/scrollex

Quick Start

import { VirtualList } from '@oxog/scrollex'

function App() {
  const items = Array.from({ length: 10000 }, (_, i) => ({
    id: i,
    name: `Item ${i + 1}`,
  }))

  return (
    <VirtualList
      data={items}
      itemHeight={50}
      height={400}
      renderItem={({ item, style }) => (
        <div style={style}>{item.name}</div>
      )}
    />
  )
}

Components

VirtualList

Efficiently render large lists with fixed or variable heights.

import { VirtualList } from '@oxog/scrollex'

<VirtualList
  data={items}
  itemHeight={50}
  height={400}
  overscan={5}
  renderItem={({ item, index, style }) => (
    <div style={style}>
      {item.name}
    </div>
  )}
/>

Variable Heights:

<VirtualList
  data={items}
  itemHeight="auto"
  estimatedItemHeight={60}
  renderItem={({ item, style, measureRef }) => (
    <div ref={measureRef} style={style}>
      {item.content}
    </div>
  )}
/>

VirtualGrid

Multi-column grid virtualization.

import { VirtualGrid } from '@oxog/scrollex'

<VirtualGrid
  data={products}
  columns={4}
  itemHeight={200}
  gap={16}
  height={600}
  renderItem={({ item, style }) => (
    <div style={style}>
      <ProductCard product={item} />
    </div>
  )}
/>

VirtualMasonry

Pinterest-style masonry layout.

import { VirtualMasonry } from '@oxog/scrollex'

<VirtualMasonry
  data={images}
  columns={3}
  gap={8}
  height={800}
  getItemHeight={(item, columnWidth) =>
    (item.height / item.width) * columnWidth
  }
  renderItem={({ item, style, width }) => (
    <div style={style}>
      <img src={item.url} width={width} alt={item.alt} />
    </div>
  )}
/>

Hooks

For more control, use the hooks directly:

import { useRef } from 'react'
import { useVirtualList } from '@oxog/scrollex'

function MyList({ items }: { items: { name: string }[] }) {
  const containerRef = useRef<HTMLDivElement>(null)

  const { virtualItems, totalSize, scrollToIndex } = useVirtualList({
    count: items.length,
    estimatedItemHeight: 50,
    containerRef,
    overscan: 5,
  })

  return (
    <div ref={containerRef} style={{ height: 400, overflow: 'auto' }}>
      <div style={{ height: totalSize, position: 'relative' }}>
        {virtualItems.map((virtualItem) => (
          <div
            key={virtualItem.key}
            style={{
              position: 'absolute',
              top: virtualItem.start,
              height: virtualItem.size,
              width: '100%',
            }}
          >
            {items[virtualItem.index]?.name}
          </div>
        ))}
      </div>
    </div>
  )
}
  • getItemHeight: (index) => number gives known row heights: every row is laid out at its height up front (totalSize, offsets, scrollToIndex), with or without measureElement. Unknown heights use estimatedItemHeight until rows are measured.
  • scrollMargin is the space above the list inside the same scroll container (a header, say). The visible range and scrollToIndex account for it; virtualItem.start and totalSize stay relative to the list element.
  • Scroll anchoring is on by default: when rows above the viewport are measured at a size other than their estimate, the scroll position moves by the difference so the rows on screen stay where they are. Pass scrollAnchoring: false (or scrollAnchoring={false} on VirtualList) to opt out. scrollToIndex also keeps re-targeting for a few frames after it lands (or after a smooth scroll ends) while the rows around the target are measured.

Plugins

Extend functionality with optional plugins:

import { VirtualList } from '@oxog/scrollex'
import { infiniteLoaderPlugin, debugPanel, DebugPanelOverlay } from '@oxog/scrollex/plugins'

// Create the debug panel once (outside render or in useMemo): the overlay reads its state
const debug = debugPanel({ position: 'bottom-right' })

<>
  <VirtualList
    data={items}
    itemHeight={50}
    plugins={[
      infiniteLoaderPlugin({
        threshold: 200,
        onLoadMore: async (direction) => {
          const newItems = await fetchMore(direction)
          setItems(prev => [...prev, ...newItems])
        }
      }),
      debug,
    ]}
    renderItem={({ item, style }) => (
      <div style={style}>{item.name}</div>
    )}
  />
  <DebugPanelOverlay plugin={debug} />
</>

Available Plugins

Plugin Description
listRendererPlugin Core list rendering
gridRendererPlugin Grid layout rendering
autoMeasurerPlugin Automatic height measurement
infiniteLoaderPlugin Infinite scroll loading
scrollControllerPlugin Programmatic scroll control
debugPanel + DebugPanelOverlay Visual debugging tools

VirtualList, VirtualGrid and their hooks already register listRendererPlugin / gridRendererPlugin themselves: passing one in plugins throws "already registered". Use them directly only with a kernel.

Errors thrown by your callbacks when the list calls them on its own (plugin options such as onLoadMore, onReorder or onFocus, plugin hooks, kernel.on() listeners, the components' onScroll, run from a scroll, a key, a drag or a kernel event), and rejections of the promises they return, are logged with console.error under a [Scrollex] prefix, and the list finishes its own work (the drag ends, infinite loading still triggers). A call you make yourself, such as kernel.register() with a throwing install or keyboardNav's setFocusedIndex(), throws the error back to you; renderItem, onVisibleRangeChange and onItemsRendered run while React renders and their errors reach your error boundary.

Infinite Scroll

import { useState } from 'react'
import { VirtualList } from '@oxog/scrollex'
import { infiniteLoaderPlugin } from '@oxog/scrollex/plugins'

function InfiniteList() {
  const [items, setItems] = useState(initialItems)
  const [loading, setLoading] = useState(false)

  const handleLoadMore = async (direction: 'forward' | 'backward') => {
    if (loading) return
    setLoading(true)

    const newItems = await fetchMoreItems(direction)
    setItems(prev =>
      direction === 'forward'
        ? [...prev, ...newItems]
        : [...newItems, ...prev]
    )

    setLoading(false)
  }

  return (
    <VirtualList
      data={items}
      itemHeight={50}
      height={400}
      plugins={[
        infiniteLoaderPlugin({
          threshold: 200,
          onLoadMore: handleLoadMore,
        })
      ]}
      renderItem={({ item, style }) => (
        <div style={style}>{item.name}</div>
      )}
    />
  )
}

Performance

Scrollex is designed for maximum performance:

  • Binary Search - O(log n) visible range calculation
  • Measurement Caching - Efficient variable height handling
  • RAF Batching - Scroll handling is throttled to animation frames
  • CSS Containment - Optimized paint and layout

The kernel is tested with lists of 100,000+ items; only the rows in view (plus overscan) are mounted.

Bundle size

Measured for 1.1.1 with esbuild (minified, react external):

Import min min+gzip
any single export of @oxog/scrollex (useVirtualList, VirtualList, createKernel) ~41KB ~11.7KB
everything from @oxog/scrollex ~50KB ~14.2KB
everything from @oxog/scrollex/plugins ~30KB ~10.0KB

The entries share one chunk, so importing a single export costs about as much as the core.

Browser Support

  • Chrome 80+
  • Firefox 75+
  • Safari 13.1+
  • Edge 80+

Documentation

Full documentation available at scrollex.oxog.dev

Contributing

Contributions are welcome! Please read our Contributing Guide for details.

# Clone the repository
git clone https://github.com/ersinkoc/Scrollex.git

# Install dependencies
npm install

# Run tests
npm test

# Start development
npm run dev

Author

Ersin KOC - @ersinkoc

License

MIT License - see the LICENSE file for details.


Built with care by Ersin KOC

About

Zero-dependency React virtualization library with micro-kernel plugin architecture

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

0