How to Optimize Large JSON Data Rendering in React

Muhaymin Bin Mehmood

Muhaymin Bin Mehmood

·
9 min read
Published Apr 3, 2025
Updated Oct 8, 2026
How to Optimize Large JSON Data Rendering in React banner Image
13 min read
1,329 words
19 sections9 code blocks

When a React app renders a large JSON response, the slow part is almost never parsing the JSON. It's creating thousands of DOM nodes. In our test, rendering 50,000 rows as plain <div>s took 2.1 seconds; a virtualized list showed the same data in 3 ms with only 15 rows in the DOM.

Quick answer: don't render every item. Virtualize long lists (react-window), or paginate on the server. Then make filtering, streaming and state updates cheap. This guide shows each technique with code that runs on today's versions of the libraries.

Tested with: React 19.3 (production build), react-window 2.3, TanStack Query 5.104 and Zustand 5.0 in Chrome 152, October 2026. Numbers will vary by device; the differences between them won't.

Why Large JSON Data Makes React Slow

There are three separate costs, and they're very different in size:

  • Parsing: JSON.parse on a 16.9 MB array of 200,000 objects took 83 ms. Noticeable, but rarely the main problem.
  • Rendering: every item becomes React elements and DOM nodes. This grows with the number of items and is where seconds are lost.
  • Re-rendering: each state change (typing in a filter, a new page, a store update) can re-render the whole list again.

Measured: plain rendering vs virtualization

RowsRender every rowreact-window ListRows in the DOM (virtualized)
1,00029 ms1 ms15
10,000362 ms1 ms15
50,0002,130 ms3 ms15

Median of three renders, 400 px tall list, 36 px rows.

1. Virtualize Long Lists with react-window

react-window renders only the rows that are visible (plus a few extra), and swaps them as the user scrolls. Install it with npm install react-window.

JSX
import { List } from "react-window";

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

export function VirtualizedList({ items }) {
  return (
    <List
      rowComponent={Row}
      rowCount={items.length}
      rowHeight={36}
      rowProps={{ items }}
      style={{ height: 400 }}
    />
  );
}
  • This is the react-window 2 API. Version 2 replaced FixedSizeList with List, rowComponent, rowCount, rowHeight and rowProps. Code that imports FixedSizeList fails to build against version 2 with "No matching export".
  • rowProps passes data to each row; don't read the list from a closure.
  • Spread ariaAttributes onto the row: it adds role="listitem", aria-posinset and aria-setsize, so screen readers know where they are in a 50,000-item list.
  • Fixed row heights are fastest. For rows of different heights, react-window 2 provides useDynamicRowHeight.

Scrolling to the bottom of 50,000 rows rendered row 50,000 while the DOM still held fewer than 25 rows.

2. Paginate on the Server with TanStack Query

If the API supports it, don't download everything — ask for one page at a time. With TanStack Query (React Query) v5:

JSX
import { useState } from "react";
import { useQuery, keepPreviousData } from "@tanstack/react-query";

const PAGE_SIZE = 20;

async function fetchProducts(page) {
  const skip = (page - 1) * PAGE_SIZE;
  const res = await fetch(
    `https://dummyjson.com/products?limit=${PAGE_SIZE}&skip=${skip}&select=title,price`
  );
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json(); // { products, total, skip, limit }
}

export function PaginatedProducts() {
  const [page, setPage] = useState(1);
  const { data, isPending, isError, error, isPlaceholderData } = useQuery({
    queryKey: ["products", page],
    queryFn: () => fetchProducts(page),
    placeholderData: keepPreviousData, // keep showing the old page while the next one loads
  });

  if (isPending) return <p>Loading…</p>;
  if (isError) return <p>Error: {error.message}</p>;

  const totalPages = Math.ceil(data.total / PAGE_SIZE);

  return (
    <div style={{ opacity: isPlaceholderData ? 0.6 : 1 }}>
      <ul>
        {data.products.map((p) => (
          <li key={p.id}>
            {p.title} — ${p.price}
          </li>
        ))}
      </ul>
      <button onClick={() => setPage((n) => n - 1)} disabled={page === 1}>
        Previous
      </button>
      <span> Page {page} of {totalPages} </span>
      <button
        onClick={() => setPage((n) => n + 1)}
        disabled={isPlaceholderData || page === totalPages}
      >
        Next
      </button>
    </div>
  );
}

Wrap your app in a QueryClientProvider once:

JSX
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { PaginatedProducts } from "./PaginatedProducts";

const queryClient = new QueryClient();

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <PaginatedProducts />
    </QueryClientProvider>
  );
}
  • v5 only accepts the object form: useQuery({ queryKey, queryFn }). The old useQuery(["items", page], fetchItems) throws "Bad argument type" in development.
  • placeholderData: keepPreviousData keeps the current page on screen (dimmed here) while the next one loads, instead of flashing "Loading…".
  • Next is disabled while the placeholder is shown and on the last page, so users can't skip past the end.
  • Pages you've already seen come from the cache: going back to page 1 was instant in our test.

See TanStack's paginated queries guide for infinite scrolling with useInfiniteQuery.

3. Filter Large Lists Without Freezing the Input

JSX
import { useDeferredValue, useMemo, useState } from "react";
import { VirtualizedList } from "./VirtualizedList";

export function SearchableList({ items }) {
  const [query, setQuery] = useState("");
  const deferredQuery = useDeferredValue(query); // typing stays responsive while filtering

  const filtered = useMemo(() => {
    const q = deferredQuery.trim().toLowerCase();
    if (!q) return items;
    return items.filter((item) => item.name.toLowerCase().includes(q));
  }, [items, deferredQuery]);

  return (
    <>
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Filter by name…"
      />
      <p>{filtered.length.toLocaleString()} rows</p>
      <VirtualizedList items={filtered} />
    </>
  );
}
  • useMemo re-filters only when the items or the query change, not on every render.
  • useDeferredValue lets React update the input first and run the filter as a lower-priority update, so typing doesn't stutter on slow devices.
  • Filtering 100,000 objects took about 19 ms. Rendering the results is the expensive part, which is why the filtered list is virtualized.

4. Stream Large Responses as NDJSON

A single large JSON array can't be used until the whole response has arrived and been parsed. If you control the API, send newline-delimited JSON (NDJSON) instead — one object per line:

JSON
{"id":1,"name":"Ana","email":"ana@example.com"}
{"id":2,"name":"Bo","email":"bo@example.com"}
{"id":3,"name":"Cy","email":"cy@example.com"}

Then read it line by line as it arrives:

JavaScript
export async function* streamNdjson(url, { signal } = {}) {
  const res = await fetch(url, { signal });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);

  // TextDecoderStream handles characters split across chunks
  const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
  let buffer = "";

  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    buffer += value;
    const lines = buffer.split("\n");
    buffer = lines.pop(); // the last line may be incomplete
    for (const line of lines) {
      if (line.trim()) yield JSON.parse(line);
    }
  }
  if (buffer.trim()) yield JSON.parse(buffer);
}

And render rows as they stream in:

JSX
import { useEffect, useState } from "react";
import { streamNdjson } from "./streamNdjson";
import { VirtualizedList } from "./VirtualizedList";

const BATCH_SIZE = 500;

export function StreamedRows({ url }) {
  const [rows, setRows] = useState([]);
  const [done, setDone] = useState(false);

  useEffect(() => {
    const controller = new AbortController();
    setRows([]);
    setDone(false);

    (async () => {
      let batch = [];
      try {
        for await (const row of streamNdjson(url, { signal: controller.signal })) {
          batch.push(row);
          if (batch.length === BATCH_SIZE) {
            const chunk = batch;
            setRows((prev) => prev.concat(chunk)); // one render per 500 rows, not per row
            batch = [];
          }
        }
        setRows((prev) => prev.concat(batch));
        setDone(true);
      } catch (err) {
        if (err.name !== "AbortError") console.error(err);
      }
    })();

    return () => controller.abort();
  }, [url]);

  return (
    <>
      <p>
        {rows.length.toLocaleString()} rows {done ? "loaded" : "so far…"}
      </p>
      <VirtualizedList items={rows} />
    </>
  );
}
  • Decode with a stream-aware decoder. A network chunk can end in the middle of a character. Calling new TextDecoder().decode(chunk) on each chunk separately turned "Usér" into "Us��r" in our test. TextDecoderStream (or decode(chunk, { stream: true })) keeps the partial bytes for the next chunk.
  • Don't JSON.parse raw chunks. A chunk is an arbitrary slice of bytes, not a complete JSON value. Splitting on newlines and keeping the incomplete last line is what makes this work.
  • Batch state updates. Calling setRows once per row means one render per row. Adding 500 rows at a time kept 20,000 streamed rows to a few dozen renders.
  • Abort on unmount so a stream doesn't keep writing state into a component that's gone.

5. Memoize Rows That Don't Change

When a parent re-renders for an unrelated reason — say, typing in a notes field above the list — every row re-renders too, even though none of them changed. React.memo skips rows whose props are the same:

JSX
import { memo, useState } from "react";

const ProductRow = memo(function ProductRow({ product }) {
  return (
    <li className="row">
      {product.name} — {product.email}
    </li>
  );
});

export function ProductPage({ products }) {
  const [note, setNote] = useState("");

  return (
    <>
      <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="Notes…" />
      <ul>
        {products.map((p) => (
          <ProductRow key={p.id} product={p} />
        ))}
      </ul>
    </>
  );
}

With 2,000 rows, one keystroke took 6.2 ms without memo and 3.1 ms with it. Worth having, but nowhere near the gain from not rendering 2,000 rows in the first place. Memoization only works if the props really are the same objects: creating new objects or inline functions for each row on every render defeats it.

6. Where to Keep Large Data: useState or a Store?

Moving data from useState into Redux, Zustand or Jotai doesn't make it render faster — the list still has to render its items. What a store can do is let components subscribe to just the piece they need. With Zustand 5:

JSX
import { create } from "zustand";

export const useDataStore = create((set) => ({
  items: [],
  status: "idle",
  load: async (url) => {
    set({ status: "loading" });
    try {
      const res = await fetch(url);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      set({ items: await res.json(), status: "done" });
    } catch {
      set({ status: "error" });
    }
  },
}));

// Subscribe to the smallest piece of state each component needs
export function ItemCount() {
  const count = useDataStore((state) => state.items.length);
  return <p>{count} items</p>;
}
  • Import create as a named export. Zustand 5 has no default export, so import create from "zustand" fails to build.
  • Use selectors. In our test, a component that called useDataStore() with no selector re-rendered on every store change; components that selected state.status or state.items.length only re-rendered when that value changed.

7. Move Heavy Processing Off the Main Thread

A Web Worker can fetch, parse and process data without blocking the UI, but sending the result back with postMessage copies it. Copying 200,000 objects with structuredClone (the algorithm postMessage uses) took 229 ms in our test — longer than JSON.parse took for the same data (83 ms).

So a worker pays off when it reduces the data — filtering, aggregating, sorting and sending back only the page or summary you'll show. Parsing in a worker and posting the whole array back usually makes things worse.

Common Mistakes to Avoid

MistakeWhat happensDo this instead
Rendering every itemSeconds per render at 10,000+ rowsVirtualize or paginate
Copying react-window 1 examplesFixedSizeList doesn't exist in v2Use List with rowComponent and rowProps
Old React Query signature"Bad argument type" in v5useQuery({ queryKey, queryFn })
Expecting a global store to speed up renderingSame render cost, plus whole-store re-rendersVirtualize; use selectors
setState once per streamed rowThousands of rendersBatch rows
Decoding stream chunks independentlyBroken charactersTextDecoderStream
Using React.lazy for dataIt splits component code, not JSONFetch or import data when it's needed

FAQs

Why is my React app slow with large JSON data?

Usually because it renders every item. Rendering 50,000 rows took over two seconds in our test, while parsing a much larger JSON file took under 100 ms. Render only what's visible.

How many rows can React render before it gets slow?

In our test, 1,000 simple rows took about 30 ms and 10,000 took about 360 ms. Beyond a few thousand rows, or with complex rows, virtualize.

Should I use react-window or react-virtualized?

react-window is the smaller, actively maintained successor by the same author. Note that version 2 changed the API (List instead of FixedSizeList).

Pagination or virtualization?

Paginate when the data lives on a server and users don't need everything at once. Virtualize when the data is already in the browser and users expect to scroll through it. You can combine them with infinite scrolling.

Do useMemo and React.memo fix large lists?

They reduce repeated work — memoized rows halved the time per keystroke in our test — but they don't reduce how many rows you render. Use them together with virtualization or pagination.

How do I load a huge JSON file progressively?

Serve it as NDJSON and read it with fetch, TextDecoderStream and a line splitter, adding rows in batches. A regular JSON array can't be parsed until it has fully downloaded.

Do Web Workers help with large JSON?

Only if the worker reduces the data before sending it back. Posting a large array back to the main thread copies it, which can cost more than parsing it.

Does server-side rendering help?

SSR sends the first screen as HTML, which helps initial load and SEO. It doesn't make rendering 50,000 rows cheaper: the browser still has to build those DOM nodes and React still has to hydrate them. Paginate or virtualize there too.

No comments yet. Be the first to comment!

Leave a Comment

2000 characters remaining

Related Articles

View all
Muhaymin Bin Mehmood

About Muhaymin Bin Mehmood

Front-end Developer skilled in the MERN stack, experienced in web and mobile development. Proficient in React.js, Node.js, and Express.js, with a focus on client interactions, sales support, and high-performance applications.