Infinite Masonry

A virtualized masonry grid that loads more as you near the end.

Preview

"use client";

import { useCallback, useState } from "react";
import { InfiniteMasonry } from "@/components/motion/infinite-masonry";

type GalleryItem = {
  id: string;
  title: string;
  category: string;
  image: string;
  imageHeight: number;
};

const PAGE_SIZE = 6;
const MAX_ITEMS = 42;

const gallerySource = [
  {
    title: "Soft geometry",
    category: "Architecture",
    image:
      "https://images.unsplash.com/photo-1511818966892-d7d671e672a2?auto=format&fit=crop&w=720&q=80",
    imageHeight: 260,
  },
  {
    title: "Open horizon",
    category: "Landscape",
    image:
      "https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?auto=format&fit=crop&w=720&q=80",
    imageHeight: 190,
  },
  {
    title: "Working rhythm",
    category: "Workspace",
    image:
      "https://images.unsplash.com/photo-1497366754035-f200968a6e72?auto=format&fit=crop&w=720&q=80",
    imageHeight: 230,
  },
  {
    title: "Shared table",
    category: "Studio",
    image:
      "https://images.unsplash.com/photo-1524758631624-e2822e304c36?auto=format&fit=crop&w=720&q=80",
    imageHeight: 300,
  },
  {
    title: "In session",
    category: "People",
    image:
      "https://images.unsplash.com/photo-1521737711867-e3b97375f902?auto=format&fit=crop&w=720&q=80",
    imageHeight: 210,
  },
  {
    title: "After hours",
    category: "Office",
    image:
      "https://images.unsplash.com/photo-1504384308090-c894fdcc538d?auto=format&fit=crop&w=720&q=80",
    imageHeight: 280,
  },
] as const;

function createItems(start: number, count: number): GalleryItem[] {
  return Array.from({ length: count }, (_, offset) => {
    const index = start + offset;
    const source = gallerySource[index % gallerySource.length];

    return {
      ...source,
      id: `gallery-${index}`,
      title: `${source.title} ${Math.floor(index / gallerySource.length) + 1}`,
    };
  });
}

export function InfiniteMasonryPreview() {
  const [items, setItems] = useState(() => createItems(0, 12));
  const [loading, setLoading] = useState(false);
  const hasMore = items.length < MAX_ITEMS;

  const loadMore = useCallback(async () => {
    if (loading || !hasMore) return;
    setLoading(true);

    await new Promise((resolve) => setTimeout(resolve, 650));
    setItems((current) => {
      const count = Math.min(PAGE_SIZE, MAX_ITEMS - current.length);
      return count > 0
        ? [...current, ...createItems(current.length, count)]
        : current;
    });
    setLoading(false);
  }, [hasMore, loading]);

  return (
    <div className="w-full max-w-5xl">
      <div className="mb-3 flex items-end justify-between gap-4 px-1">
        <div>
          <p className="text-sm font-medium text-foreground">Visual index</p>
          <p className="mt-0.5 text-xs text-muted-foreground">
            Scroll to load the next page
          </p>
        </div>
        <p className="font-mono text-xs tabular-nums text-muted-foreground">
          {items.length} items
        </p>
      </div>

      <InfiniteMasonry
        items={items}
        getItemKey={(item) => item.id}
        renderItem={(item) => (
          <figure className="overflow-hidden rounded-2xl border border-border bg-card">
            <div
              className="relative w-full overflow-hidden"
              style={{ height: item.imageHeight }}
            >
              <img
                src={item.image}
                alt={item.title}
                loading="lazy"
                decoding="async"
                className="absolute inset-0 size-full object-cover"
              />
            </div>
            <figcaption className="flex items-start justify-between gap-3 p-3">
              <p className="text-sm font-medium text-foreground">
                {item.title}
              </p>
              <p className="shrink-0 text-[11px] uppercase tracking-wider text-muted-foreground">
                {item.category}
              </p>
            </figcaption>
          </figure>
        )}
        onLoadMore={loadMore}
        hasMore={hasMore}
        loading={loading}
        estimateSize={(item) => item.imageHeight + 66}
        ariaLabel="Visual inspiration gallery"
        className="h-[34rem]"
      />
    </div>
  );
}

Install

Add it with the shadcn CLI, or copy the source manually.

$ bunx --bun shadcn add @beui/infinite-masonry

API Reference

items
readonly T[]

The items loaded so far, in feed order.

getItemKey
(item: T, index: number) => InfiniteMasonryKey

Returns a stable unique key for an item.

renderItem
(item: T, index: number) => ReactNode

Renders one item's card.

onLoadMore
() => void | Promise<void>

Called when the scroll nears the end and more items should load.

hasMore
boolean

Whether more items can load. False shows `endState` after the last item.

loading?
boolean

Shows loading placeholders at the end while more items load. Default: false

Defaultfalse
error?
ReactNode

Error shown in a card at the end. Pauses loading while set.

onRetry?
(() => void)

Called from the error card's retry button. The button shows only when set.

estimateSize?
((item: T, index: number) => number)

Estimated item height in px before it is measured. Default: 240

Default() => 240
renderLoadingItem?
((index: number) => ReactNode)

Renders a loading placeholder card while more items load.

Default(index) => <DefaultLoadingItem index={index} />
emptyState?
ReactNode

Shown when there are no items and nothing more to load.

endState?
ReactNode

Shown below the last item once `hasMore` is false.

minColumnWidth?
number

Smallest column width in px before a column is dropped. Default: 208

Default208
maxColumns?
number

Most columns to show. Default: 4

Default4
gap?
number

Space between items in px. Default: 12

Default12
overscan?
number

Rows to render past the viewport, per column. Default: 4

Default4
prefetch?
number

Starts loading when this many items from the end are visible. Default: 3

Default3
animateItems?
boolean

Fades and slides in items added after the first render. Default: true

Defaulttrue
ariaLabel?
string

Accessible name for the feed. Default: "Infinite masonry feed"

className?
string

Classes merged onto the scroll container.

contentClassName?
string

Classes merged onto the inner content element that holds the items.

itemClassName?
string

Classes merged onto each item wrapper, not loading or error cards.

labels?
Partial<{ label: string; emptyTitle: string; emptyDescription: string; loadError: string; retry: string; loadingMore: string; }>

Override any built-in string.

Keep in mind

Some components on this site are inspired by or recreated from existing work across the web. I'm not here to take credit; just to learn, experiment, and sometimes push things a bit further. If something looks familiar and I forgot to mention you, reach out and I'll fix that right away.

Updated