Skip to content

SilverBirchh/use-lazy-grid

Repository files navigation

use-lazy-grid

Lazily render a list of items

NPM JavaScript Style Guide

Take a long list of flex or grid items and lazy load them in to the DOM with ease.

Install

npm install --save use-lazy-grid

API

useLazyGrid

const visibleItems = useLazyGrid({
    size,
    gridRef,
    estimateSize,
    overscan,
})
Options
  • size: number

    • Required
    • The total count of elements
  • gridRef: React.useRef(DOMElement)

    • Required
    • The parent grid element
  • estimateSize: number

    • Required
    • The estime height in px of the grid elements
  • overscan: number

    • Defaults to 5
    • The number of row to ahead of the current window range

Usage

import React, { useRef } from "react";

import useLazyGrid from "use-lazy-grid";

const items = new Array(10000).fill(0);

const App = () => {
  const parentRef = useRef(null);

  const visible = useLazyGrid({
    size: items.length,
    gridRef: parentRef,
    estimateSize: 100,
  });

  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "repeat(4, 1fr)",
        gap: 20,
      }}
      ref={parentRef}
    >
      {visible.map(({ index }) => {
        return (
          <div
            key={index}
            style={{
              height: 100,
              borderRadius: 5,
              backgroundColor: "#F56565",
            }}
          />
        );
      })}
    </div>
  );
};

License

MIT © SilverBirchh


This hook is created using create-react-hook.