StackPractices
intermediate By Mathias Paulenko

Virtualize Long Lists with react-window

How to render large lists efficiently in React with react-window 2, covering the List and Grid components, dynamic row heights, and infinite scrolling.

Topics: frontend

Overview

react-window renders only the rows a user can actually see, recycling DOM nodes as they scroll. Instead of mounting 10,000 <div> elements, a long list keeps roughly a screenful of rows plus a small overscan buffer, so the DOM stays small and scrolling stays smooth.

Version 2 of the package rebuilt the API around two components: List for vertical lists and Grid for two-dimensional layouts. Row height can be a fixed number, a function of the index, or measured automatically for dynamic content. This recipe uses that API throughout; if you maintain an older react-window 1.x codebase, the concepts still apply but the component names differ.

When to Use

  • Lists with 1,000+ items where mounting everything at once causes jank
  • Tables with large datasets that need smooth scrolling
  • Grid layouts with many cells
  • Chat message lists with thousands of messages
  • Any list where rendering every item inflates memory use or initial render time

When NOT to Use

  • Lists with fewer than ~100 items — virtualization overhead isn’t worth it
  • Lists whose content must exist in the DOM for SEO, printing, or browser find (Ctrl+F) — off-screen rows aren’t rendered until scrolled into view
  • Rows with heights you can’t estimate at all and can’t measure after render — a library like react-virtuoso handles unknown sizes with less setup

Solution

Setup

npm install react-window

The examples below require react-window 2.x or later.

Fixed-height list

import { List } from "react-window";

const items = Array.from({ length: 10000 }, (_, i) => `Item ${i}`);

function RowComponent({ index, style, ariaAttributes, items }) {
  return (
    <div style={style} className="list-row" {...ariaAttributes}>
      {items[index]}
    </div>
  );
}

function VirtualList() {
  return (
    <List
      rowComponent={RowComponent}
      rowProps={{ items }}
      rowCount={items.length}
      rowHeight={50}
      style={{ height: 600 }}
    />
  );
}

The style prop that react-window injects into each row positions it absolutely, so apply it to the row’s root element without overriding it. Spread ariaAttributes onto the same element — it adds the role="listitem" and position metadata that screen readers and height measurement rely on.

Variable height rows

import { List } from "react-window";

const items = Array.from({ length: 1000 }, (_, i) => ({
  id: i,
  text: `Item ${i} — ${"x".repeat((i % 5) + 1) * 20}`,
}));

function RowComponent({ index, style, ariaAttributes, items }) {
  return (
    <div style={style} className="list-row" {...ariaAttributes}>
      <h4>{items[index].text}</h4>
    </div>
  );
}

function VariableList() {
  return (
    <List
      rowComponent={RowComponent}
      rowProps={{ items }}
      rowCount={items.length}
      rowHeight={(index) => 40 + ((index % 5) + 1) * 24}
      style={{ height: 600 }}
    />
  );
}

rowHeight also accepts the object returned by useDynamicRowHeight for rows whose height must be measured after rendering, and the string "dynamic" shorthand.

Grid layout

import { Grid } from "react-window";

function Cell({ columnIndex, rowIndex, style, ariaAttributes }) {
  return (
    <div style={style} className="grid-cell" {...ariaAttributes}>
      Row {rowIndex}, Col {columnIndex}
    </div>
  );
}

function VirtualGrid() {
  return (
    <Grid
      cellComponent={Cell}
      cellProps={{}}
      columnCount={4}
      columnWidth={200}
      rowCount={2500}
      rowHeight={100}
      style={{ height: 600, width: 800 }}
    />
  );
}

Infinite scrolling

onRowsRendered reports the visible row range on every scroll, which is the supported way to trigger the next fetch — no reading internals from a ref:

import { List } from "react-window";
import { useRef, useState } from "react";

function InfiniteList() {
  const [items, setItems] = useState(() =>
    Array.from({ length: 50 }, (_, i) => `Item ${i}`)
  );
  const [hasMore, setHasMore] = useState(true);
  const loadingRef = useRef(false);

  function handleRowsRendered({ stopIndex }) {
    if (loadingRef.current || !hasMore || stopIndex < items.length - 5) return;
    loadingRef.current = true;
    setTimeout(() => {
      setItems((prev) => {
        const next = [
          ...prev,
          ...Array.from({ length: 50 }, (_, i) => `Item ${prev.length + i}`),
        ];
        if (next.length >= 10000) setHasMore(false);
        return next;
      });
      loadingRef.current = false;
    }, 400);
  }

  function RowComponent({ index, style, ariaAttributes, items, hasMore }) {
    if (index >= items.length) {
      return (
        <div style={style} className="loading-row" {...ariaAttributes}>
          Loading more…
        </div>
      );
    }
    return (
      <div style={style} className="list-row" {...ariaAttributes}>
        {items[index]}
      </div>
    );
  }

  return (
    <List
      rowComponent={RowComponent}
      rowProps={{ items, hasMore }}
      rowCount={items.length + (hasMore ? 1 : 0)}
      rowHeight={50}
      onRowsRendered={handleRowsRendered}
      style={{ height: 600 }}
    />
  );
}

Reserving the last rowCount slot for a loading row is optional; for server pagination, react-window-infinite-loader wraps the same pattern.

Scroll to a row

import { List, useListRef } from "react-window";

function ListWithScroll({ items }) {
  const listRef = useListRef();

  return (
    <div>
      <button
        onClick={() =>
          listRef.current?.scrollToRow({
            index: 500,
            align: "center",
            behavior: "smooth",
          })
        }
      >
        Jump to item 500
      </button>
      <List
        listRef={listRef}
        rowComponent={RowComponent}
        rowProps={{ items }}
        rowCount={items.length}
        rowHeight={50}
        style={{ height: 600 }}
      />
    </div>
  );
}

scrollToRow throws a RangeError for out-of-bounds indexes, so clamp the index when the target row can change.

Horizontal scrolling

A horizontal strip is a Grid with a single row — grids scroll both axes natively:

import { Grid } from "react-window";

function CardCell({ columnIndex, style, ariaAttributes }) {
  return (
    <div style={style} className="horizontal-card" {...ariaAttributes}>
      Card {columnIndex}
    </div>
  );
}

function HorizontalList() {
  return (
    <Grid
      cellComponent={CardCell}
      cellProps={{}}
      columnCount={1000}
      columnWidth={160}
      rowCount={1}
      rowHeight={120}
      style={{ height: 140 }}
    />
  );
}

Page-level scrolling

Version 2 drops the WindowScroller wrapper: set scrollElement="window" and the list scrolls with the page instead of its own container.

<List
  scrollElement="window"
  rowComponent={RowComponent}
  rowProps={{ items }}
  rowCount={items.length}
  rowHeight={50}
/>

Explanation

Virtualization keeps a fixed window of mounted rows around the scroll position. When the user scrolls, react-window recycles the rows that leave the viewport and mounts the ones entering it, so DOM size depends on the viewport — not the dataset. overscanCount (default 3) renders a few extra rows on each side to hide the swap during fast scrolling; raise it for rows that are expensive to mount.

A virtualized list of 10,000 items only mounts the visible rows plus an overscan buffer; scrolling recycles rows in and out of the small DOM window.

Three things control what a row costs:

  • rowHeight accuracy. Fixed numbers are cheapest because offsets are pure arithmetic. A height function adds a per-index lookup. useDynamicRowHeight measures rendered rows and adjusts positions as sizes resolve, which is correct but the noisiest scroll path.
  • Row component work. Visible rows re-render when the window moves. Wrapping the row in React.memo and passing data through rowProps lets unchanged rows skip that work.
  • rowProps identity. The list re-renders rows when values inside rowProps change. Keep the object fields stable; recreating data on every parent render defeats the memoization.

Keep item arrays immutable: when the same array instance is passed via rowProps, unchanged rows are free.

Variants

With data fetching

function DataList({ data, loading, onLoadMore }) {
  function RowComponent({ index, style, ariaAttributes, data, loading }) {
    if (index >= data.length) {
      return (
        <div style={style} className="loading-row" {...ariaAttributes}>
          {loading ? "Loading…" : "Load more"}
        </div>
      );
    }
    return (
      <div style={style} className="list-row" {...ariaAttributes}>
        <strong>{data[index].name}</strong>
        <span>{data[index].email}</span>
      </div>
    );
  }

  return (
    <List
      rowComponent={RowComponent}
      rowProps={{ data, loading }}
      rowCount={data.length + 1}
      rowHeight={60}
      style={{ height: 600 }}
      onRowsRendered={({ stopIndex }) => {
        if (stopIndex >= data.length - 5 && !loading) onLoadMore();
      }}
    />
  );
}

Memoized row components

import { memo } from "react";

const MemoizedRow = memo(function Row({ index, style, ariaAttributes, items }) {
  const item = items[index];
  return (
    <div style={style} className="list-row" {...ariaAttributes}>
      {item.name} — {item.email}
    </div>
  );
});

function OptimizedList({ items }) {
  return (
    <List
      rowComponent={MemoizedRow}
      rowProps={{ items }}
      rowCount={items.length}
      rowHeight={50}
      style={{ height: 600 }}
    />
  );
}

rowProps replaces the old itemData prop: anything you pass there reaches every row. Combined with memo, unchanged rows skip re-rendering while scrolling — the same trade-off covered in the useMemo and useCallback recipe.

Best Practices

  • For a deeper guide, see the React performance optimization guide.
  • Prefer a fixed rowHeight when all rows share a height — offsets are pure arithmetic.
  • Reach for a height function only when sizes vary predictably, and for useDynamicRowHeight when rows must be measured.
  • Apply the injected style prop to the row’s root element and spread ariaAttributes there too.
  • Pass data through rowProps instead of closures so memoized rows can bail out of re-renders.
  • Raise overscanCount above the default 3 only if fast scrolling flashes blank rows.
  • Measure with React DevTools Profiler before and after memoizing rows; the useMemo and useCallback recipe shows how.

Common Mistakes

  • Overriding the style prop: react-window uses it to position the row. Merge extra styles instead: style={{ ...style, borderBottom: "1px solid #ccc" }}.
  • Forgetting ariaAttributes: without it, rows lose their accessibility metadata and dynamic height measurement can misfire.
  • Passing fresh objects through rowProps every render: the list re-renders rows whenever values in rowProps change, so unstable data defeats memo.
  • Recreating data the row depends on: a new items array each render is a new rowProps value. Keep it stable with state or memoization.
  • Expecting a container height to appear on its own: the list fills its parent’s width, but vertical size comes from style or defaultHeight. Set an explicit height for standalone lists.

Further Reading

Frequently Asked Questions

What is the difference between react-window and react-virtualized?

react-window is the successor to react-virtualized by the same author — smaller, faster, and with a simpler API. Version 2 collapses the old FixedSizeList/VariableSizeList/FixedSizeGrid exports into List and Grid. Reach for react-virtualized only if a legacy codebase already depends on it.

How do I handle rows with dynamic heights?

Pass a rowHeight function when heights are predictable from the data. When heights depend on rendered content, create the value with useDynamicRowHeight({ defaultRowHeight: 48 }) and pass it as rowHeight — rows are measured after mount and positions corrected. Call it again with a different key if your data changes wholesale.

Can I use react-window with TypeScript?

Yes — version 2 ships its own types, so skip @types/react-window. Type the row component with RowComponentProps:

import { RowComponentProps } from "react-window";

const Row = ({ index, style, ariaAttributes, items }: RowComponentProps<{ items: string[] }>) => (
  <div style={style} {...ariaAttributes}>Item {index}</div>
);
How do I size the list to its container?

The list measures its container for width and re-renders on resize, so a plain style={{ height: "50vh" }} (or a flex-bounded parent) is enough. For percentage rowHeight values, set defaultHeight so rows render sensibly before the container is measured — especially during SSR.

Does react-window work with server-side rendering?

Yes, with caveats. Rows can't be measured on the server, so pass defaultHeight to control how many render in the initial HTML; the real measurement kicks in after hydration. Content still isn't searchable via Ctrl+F for off-screen rows.