Software Crafting

Rendering 100k+ Rows in React: Architecting High-Performance Data Grids with Virtualization and Web Workers

BBadal SinghWeb Development8 min read06 Apr 2026Updated 2026-11-07
Endless dark grid of glowing cyan and violet light lanes with small translucent glass blocks placed along them, fading into the distance

TL;DR: Rendering 100,000+ rows in React requires more than DOM virtualization, because a synchronous sort over the full array still blocks the main thread for far longer than one frame (about 16.7ms at 60Hz). This post shows how to combine @tanstack/react-virtual with a Web Worker that sorts row indices and transfers the result back as an ArrayBuffer, so the sort runs off the main thread. It also covers CSS containment for the scroll container and the memory trade-offs of keeping a copy of the data in the worker.

Key Takeaways

  • Offload large synchronous sorts to a Web Worker to prevent main thread lockups. React's useTransition can interrupt rendering, but it cannot interrupt a single long-running Array.prototype.sort() call.
  • Have the worker return a sorted Int32Array of row indices and transfer its ArrayBuffer, so the result moves back without a structured-clone copy.
  • Implement @tanstack/react-virtual to render only the visible rows plus a small overscan buffer to eliminate DOM bloat.
  • Use fixed row heights (e.g., estimateSize: () => 35) when your design allows it, so the virtualizer does not need to measure rows while scrolling.
  • Apply contain: strict to your scroll container (with an explicit height) so layout and paint work inside it stays isolated from the rest of the page.
  • Position rows with transform: translateY(...); will-change: transform is optional and worth keeping only if profiling shows it helps.

You have a massive JSON payload containing 100,000+ rows of analytical data, system logs, or financial transactions. Your product requirements state this data must be rendered in a single, continuous, sortable grid.

You fetch the data, map() over the array, and watch memory use climb. Creating and laying out hundreds of thousands of DOM nodes blocks the Event Loop for a long time, and on low-memory devices the tab can crash.

The immediate fix is DOM virtualization. You install @tanstack/react-virtual, and the rendering issue disappears. Only 30 rows are present in the DOM at any given time. But then, the user clicks the "Sort by Revenue" column header. The UI freezes while the sort runs, hover states stop responding, and the grid stutters.

Rendering is only half of the problem. With large datasets, the JavaScript time spent sorting, filtering, and parsing is enough to block the main thread and drop frames. React's useTransition does not help here: it lets React interrupt rendering work, but a single Array.prototype.sort() call is synchronous and cannot be interrupted.

A 60Hz display gives the browser about 16.7ms per frame, so any task much longer than that causes visible jank. The fix is to move the heavy compute off the main thread.

In this guide, we will build a data grid that offloads sorting to a Web Worker, uses Transferable Objects to return results without copying, and keeps the DOM small with virtualization.

The Anatomy of a Main Thread Lockup

Before fixing the problem, we must understand exactly why modern React applications choke on large datasets. Here is a standard, naive implementation of sorting in a React component:

// Anti-pattern: the main thread bottleneck
import { useState, useMemo } from 'react';

export function StandardGrid({ data }) {
  const [sortKey, setSortKey] = useState<string>('id');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc');

  // Blocks the main thread for the full duration of the sort
  const sortedData = useMemo(() => {
    return [...data].sort((a, b) => {
      const valA = a[sortKey];
      const valB = b[sortKey];

      if (valA < valB) return sortDir === 'asc' ? -1 : 1;
      if (valA > valB) return sortDir === 'asc' ? 1 : -1;
      return 0;
    });
  }, [data, sortKey, sortDir]);

  return (
    <div>
      <button onClick={() => setSortDir((prev) => (prev === 'asc' ? 'desc' : 'asc'))}>
        Toggle Sort
      </button>
      {/* Virtualized list rendering sortedData... */}
    </div>
  );
}

When data contains 100,000 objects, [...data] allocates a new array, and Array.prototype.sort() then calls the comparator well over a million times, synchronously. While it runs, the browser cannot paint, run layout, or respond to user clicks. Measure it on your own data with the Performance panel in Chrome DevTools: any task over 50ms is flagged as a long task.

Performance Note: Profile on a mid-range laptop or phone, not only on a fast development machine. A sort that feels instant on an M-series MacBook can take several times longer on the devices your users actually have.

DOM Virtualization Is Not Enough

Virtualization solves layout thrashing by only rendering the elements currently visible in the viewport, plus a small overscan buffer. TanStack Virtual is a widely used, headless option for this.

However, the virtualizer still requires synchronous access to the data array to extract row values based on the current scroll index.

import { useVirtualizer } from '@tanstack/react-virtual';
import { useRef } from 'react';

export function VirtualizedGrid({ sortedData }) {
  const parentRef = useRef<HTMLDivElement>(null);

  const rowVirtualizer = useVirtualizer({
    count: sortedData.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 35, // Fixed row heights avoid measuring rows during scroll
    overscan: 10,
  });

  return (
    <div ref={parentRef} style={{ height: 600, overflow: 'auto', contain: 'strict' }}>
      <div
        style={{
          height: `${rowVirtualizer.getTotalSize()}px`,
          width: '100%',
          position: 'relative',
        }}
      >
        {rowVirtualizer.getVirtualItems().map((virtualRow) => {
          const item = sortedData[virtualRow.index];
          return (
            <div
              key={virtualRow.key}
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: `${virtualRow.size}px`,
                transform: `translateY(${virtualRow.start}px)`,
                willChange: 'transform',
              }}
            >
              {item.name} - {item.revenue}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Notice contain: strict on the scroll container. It tells the browser that the container's size does not depend on its children and that its contents do not affect layout or paint outside it, so work caused by row changes stays inside the container. Because strict includes size containment, the container must have an explicit height. will-change: transform promotes each row to its own compositor layer; with only a few dozen rows mounted that is usually cheap, but remove it if profiling shows high layer memory.

But as established, sortedData must be calculated somewhere. If we move the calculation to a Web Worker, we encounter an entirely new problem: serialization overhead.

Bypassing Structured Clone with the Index Mapping Pattern

When passing data between the main thread and a Web Worker via postMessage(), the browser uses the Structured Clone Algorithm to serialize and deserialize the data.

If you send a 100,000-item array of objects to a Web Worker, sort it, and send it back, the main thread has to clone the array on the way out and deserialize it on the way back. For large object arrays that can take tens to hundreds of milliseconds, so you have partly moved the main thread block from the sort to the cloning instead of eliminating it.

To solve this, we use the Index Mapping Pattern combined with Transferable Objects.

  1. The main thread keeps the immutable rawData array.
  2. We send rawData to the worker exactly once on initialization (paying the structured clone tax behind an initial skeleton loader).
  3. When a sort is requested, the worker does not sort the actual data objects. Instead, it creates an Int32Array of indices (0 to 99,999), sorts the indices based on the data, and returns the sorted Int32Array.
  4. We transfer the underlying ArrayBuffer of the Int32Array back to the main thread. Transferring moves ownership of the buffer instead of copying it, so the cost does not grow with the number of rows.

Here is the Web Worker implementation:

// data.worker.ts

// The worker holds its own copy of the dataset
let workerData: any[] = [];

self.onmessage = (event: MessageEvent) => {
  const { type, payload } = event.data;

  if (type === 'INIT') {
    // Pay the structured clone cost once during initialization
    workerData = payload.data;
    self.postMessage({ type: 'READY' });
  }

  if (type === 'SORT') {
    const { sortKey, sortDir, requestId } = payload;
    const length = workerData.length;

    // Create a typed array for indices
    const indices = new Int32Array(length);
    for (let i = 0; i < length; i++) {
      indices[i] = i;
    }

    const directionMultiplier = sortDir === 'asc' ? 1 : -1;

    // Sort the indices array by looking up values in workerData
    indices.sort((a, b) => {
      const valA = workerData[a][sortKey];
      const valB = workerData[b][sortKey];

      // Note: Use localeCompare for robust string sorting in production
      if (valA < valB) return -1 * directionMultiplier;
      if (valA > valB) return 1 * directionMultiplier;
      return 0;
    });

    // Transfer the buffer back to the main thread (Zero-Copy)
    self.postMessage(
      { type: 'SORT_COMPLETE', payload: { indices, requestId } },
      [indices.buffer], // The crucial transferable array
    );
  }
};

By transferring indices.buffer, ownership of the memory moves from the worker to the main thread without copying the 400 KB of index data (100,000 x 4 bytes). The main thread still runs your React render afterwards, but that work is limited to the visible rows.

The React Worker Hook

Now we need a type-safe React hook to manage the lifecycle of this worker and bridge the asynchronous message passing into React state.

It has to handle overlapping sort requests, component unmounting, and the loading state. Each sort carries a requestId, and the hook ignores any result that is not the latest one, so a slow earlier sort cannot overwrite a newer one.

// hooks/useDataWorker.ts
import { useEffect, useRef, useState, useCallback } from 'react';

type SortDirection = 'asc' | 'desc';

interface UseDataWorkerReturn {
  sortedIndices: Int32Array | null;
  isSorting: boolean;
  isReady: boolean;
  sortData: (key: string, dir: SortDirection) => void;
}

export function useDataWorker(rawData: any[]): UseDataWorkerReturn {
  const workerRef = useRef<Worker | null>(null);
  const latestRequestRef = useRef(0);
  const [isReady, setIsReady] = useState(false);
  const [isSorting, setIsSorting] = useState(false);

  // We store the sorted indices. Null means use default ordering.
  const [sortedIndices, setSortedIndices] = useState<Int32Array | null>(null);

  useEffect(() => {
    // New data invalidates any previous sort result
    setIsReady(false);
    setSortedIndices(null);

    // Instantiate the worker
    workerRef.current = new Worker(new URL('../workers/data.worker.ts', import.meta.url), {
      type: 'module',
    });

    const worker = workerRef.current;

    worker.onmessage = (event) => {
      const { type, payload } = event.data;

      if (type === 'READY') {
        setIsReady(true);
      }

      // Ignore results from sorts that have been superseded
      if (type === 'SORT_COMPLETE' && payload.requestId === latestRequestRef.current) {
        setSortedIndices(payload.indices);
        setIsSorting(false);
      }
    };

    // Initialize worker with data
    worker.postMessage({ type: 'INIT', payload: { data: rawData } });

    return () => {
      // Prevent memory leaks on unmount
      worker.terminate();
    };
  }, [rawData]);

  const sortData = useCallback(
    (key: string, dir: SortDirection) => {
      if (!workerRef.current || !isReady) return;
      const requestId = ++latestRequestRef.current;
      setIsSorting(true);
      workerRef.current.postMessage({
        type: 'SORT',
        payload: { sortKey: key, sortDir: dir, requestId },
      });
    },
    [isReady],
  );

  return { sortedIndices, isSorting, isReady, sortData };
}

Warning: Always call worker.terminate() in the useEffect cleanup function. A worker that is never terminated keeps its thread and its copy of the data alive after the component unmounts, which shows up as a slow memory leak in Single Page Applications (SPAs).

The High-Performance Grid Component

With the index mapping logic in a Web Worker, we combine the hook and the virtualizer into the grid component.

Notice how the virtualizer extracts the correct data object. Instead of reading sortedData[index], it reads rawData[sortedIndices[index]]. This adds one array lookup per visible row, which is negligible compared with sorting the full array on the main thread.

// components/EnterpriseGrid.tsx
import { useVirtualizer } from '@tanstack/react-virtual';
import { useRef, useState } from 'react';
import { useDataWorker } from '../hooks/useDataWorker';

interface GridProps {
  data: any[];
}

type SortConfig = { key: string; dir: 'asc' | 'desc' };

export function EnterpriseGrid({ data }: GridProps) {
  const { sortedIndices, isSorting, isReady, sortData } = useDataWorker(data);
  const [sortConfig, setSortConfig] = useState<SortConfig>({ key: 'id', dir: 'asc' });
  const parentRef = useRef<HTMLDivElement>(null);

  const handleSort = (key: string) => {
    const newDir: SortConfig['dir'] =
      sortConfig.key === key && sortConfig.dir === 'asc' ? 'desc' : 'asc';
    setSortConfig({ key, dir: newDir });
    sortData(key, newDir);
  };

  const rowVirtualizer = useVirtualizer({
    count: data.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 40,
    overscan: 10,
  });

  if (!isReady) return <div>Initializing grid...</div>;

  return (
    <div className="relative border rounded-lg border-gray-700 bg-gray-900">
      {/* Sorting Overlay */}
      {isSorting && (
        <div className="absolute inset-0 bg-black/50 z-10 flex items-center justify-center text-white">
          Sorting 100,000 rows...
        </div>
      )}

      {/* Grid Headers */}
      <div className="flex border-b border-gray-700 bg-gray-800 text-white p-2">
        <button onClick={() => handleSort('id')} className="flex-1 text-left font-bold">
          ID {sortConfig.key === 'id' && (sortConfig.dir === 'asc' ? '↑' : '↓')}
        </button>
        <button onClick={() => handleSort('revenue')} className="flex-1 text-left font-bold">
          Revenue {sortConfig.key === 'revenue' && (sortConfig.dir === 'asc' ? '↑' : '↓')}
        </button>
      </div>

      {/* Virtualized Body */}
      <div ref={parentRef} style={{ height: 800, overflow: 'auto', contain: 'strict' }}>
        <div
          style={{
            height: `${rowVirtualizer.getTotalSize()}px`,
            width: '100%',
            position: 'relative',
          }}
        >
          {rowVirtualizer.getVirtualItems().map((virtualRow) => {
            // Indirection lookup: Default to natural index if no sort is applied
            const mappedIndex = sortedIndices ? sortedIndices[virtualRow.index] : virtualRow.index;
            const item = data[mappedIndex];

            return (
              <div
                key={virtualRow.key}
                className="flex items-center text-gray-300 border-b border-gray-800 px-2"
                style={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  width: '100%',
                  height: `${virtualRow.size}px`,
                  transform: `translateY(${virtualRow.start}px)`,
                  willChange: 'transform',
                }}
              >
                <span className="flex-1 font-mono">{item.id}</span>
                <span className="flex-1 text-green-400">${item.revenue.toLocaleString()}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Memory Management and Failure Modes

At this scale, plan for the following failure modes:

  1. Out of Memory (OOM) Errors on Mobile: This pattern keeps two copies of the dataset in memory, one on the main thread and one in the worker. A JavaScript object array uses much more memory than its JSON size, so on memory-constrained phones this can crash the tab. One option is a SharedArrayBuffer (SAB), which both threads can read without copying. SAB only holds raw bytes, so you would have to store the data in a columnar, typed-array layout instead of as objects. It also requires the page to be cross-origin isolated (Cross-Origin-Opener-Policy: same-origin plus Cross-Origin-Embedder-Policy: require-corp or credentialless), which can break popup-based OAuth flows and cross-origin embeds that do not send the right headers.
  2. Detached Buffers: When you transfer a buffer (self.postMessage(data, [data.buffer])), it becomes detached in the sending context. The worker's indices array now has a length of 0, and later reads silently return undefined. Create a new Int32Array() for every sort operation, as the worker above does.
  3. Data Mutation: This architecture assumes the raw data is immutable once loaded. If your application relies on highly volatile real-time updates (like a high-frequency trading order book), you must dispatch incremental UPDATE_ROW messages to the worker to keep its internal workerData array synchronized with the main thread.

By moving the sort to a worker and limiting main-thread work to rendering the visible rows, the grid keeps responding to scrolling and clicks while a sort is in progress. The remaining limits are memory and the one-time cost of sending the data to the worker, so measure both on the lowest-end device you support. If you are building a data-heavy dashboard and want a second opinion on its architecture, our full-stack web development services cover this kind of performance work.

Sources

Available for Work

Need help building this in production?

SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.

Get a Free Consultation

Frequently Asked Questions

Why does my React UI still freeze when sorting a virtualized list?

While DOM virtualization solves layout thrashing by rendering only visible rows, it doesn't fix JavaScript execution bottlenecks. Standard array sorting operations like Array.prototype.sort() are synchronous and uninterruptible, meaning they will block the main thread and freeze the UI until the calculation finishes.

How can I prevent sorting large arrays from blocking the React main thread?

Offload heavy computations like sorting and filtering to a Web Worker. Have the worker return a sorted array of row indices as a transferable Int32Array, so the result comes back without a structured-clone copy and the main thread only renders the visible rows.

Can React's useTransition fix performance issues when sorting large datasets?

No, useTransition cannot prevent the main thread from locking up during a heavy array sort. It lets React interrupt rendering work, but a single Array.prototype.sort() call is synchronous and still blocks the Event Loop until it finishes.

What CSS properties help optimize scrolling performance in virtualized React grids?

contain: strict on the scroll container (with an explicit height) isolates its layout and paint work from the rest of the page. Positioning rows with transform: translateY(...) keeps row movement cheap, and will-change: transform can help further, but verify it in the Performance panel because each promoted layer costs memory.

About the author

Badal Singh

Co-founder of SoftwareCrafting

Badal Singh is the Co-founder of SoftwareCrafting in Delhi and writes technical guides about web and mobile development, backend security, cloud infrastructure, DevOps, and developer tooling.

Writes about Next.js, React, Node.js, PostgreSQL, React Native, Flutter.

View author profile

Last updated: 2026-11-07