← Back to Huge JSON Handling
Lesson 2.1 · Render Less

The normal list: a baseline

The normal way to show a list in React is to .map() every item to a row. It is simple and correct - and every row stays in the page. We measure that normal list at 1,000 to 100,000 orders: start-up time, memory, scrolling and one small update. These are the numbers the rest of this module tries to beat.

Beginner30 min

What you will be able to do

  • Write the normal list with .map() and a key
  • Measure mount time, DOM nodes, JS heap and tab memory as the list grows
  • Measure scrolling smoothness with frame times
  • Measure the cost of a one-item update in a big list
  • Explain why key={index} makes that update far more expensive

The idea, in plain English

The normal list is what every React tutorial teaches: orders.map((order) => <OrderRow key={order.id} order={order} />). It is easy to read, every row is a real element (so the browser’s find, select and copy all work), and for a few hundred rows it is the right choice. Module 2 is about what happens when the list is much longer.

Lesson 1.1 showed that 100,000 rows freeze the page while they are first drawn. Here we measure the whole life of the list, at four sizes: how long it takes to appear, how much memory it holds, how smooth it scrolls, and what one small change costs. These numbers are the baseline for virtual scrolling (Lesson 2.2), pagination (Lesson 2.3) and the JSON tree (Lesson 2.4).

How we measured: headless Chromium 159.0.8154.6 through playwright-core 1.65.1, React 19.2.3 bundled by esbuild 0.28.1, the same Intel Core i5-4200U laptop (4 threads, 7 GB RAM) as the earlier lessons. The page always loads the 100,000-order file and shows the first N orders. Every case ran 5 times; the numbers are medians. Memory and layout figures come from Chrome itself, through the DevTools protocol.

Worked example: The same orders table at 1,000, 10,000, 50,000 and 100,000 rows: mount time, DOM nodes, memory, scrolling frames - and the cost of removing one order with key={order.id} and key={index}.

workflowThe life of a 100,000-row liststep 1 / 3

1 - First draw: slow and heavy

All 100,000 rows go into the page at once.

mount + paint
10,249 ms
DOM nodes (with text)
1,300,015
tab memory
1,383 MB

Median of 5 runs in headless Chromium. Real results from run3.mjs.

Words you will see in this lesson

A few list and measuring words.

Small dictionary
MountThe first time React puts a component and its rows into the page.
keyA prop that tells React which item each row belongs to, so it can match rows between renders.
ReconciliationReact comparing the new list of elements with the old one to decide what to change in the DOM.
Text nodeThe text inside an element, such as “Hyderabad” in a <td>. The DOM stores it as its own node.
JS heapMemory used by JavaScript objects: the orders and React’s own data.
Tab memoryAll private memory of the tab’s renderer process: JS heap, DOM, layout data and more.
FrameOne picture on screen. At 60 frames per second a frame has about 16.7 ms.
MutationObserverA browser API that reports every change made to the DOM.

An everyday example: a phone book

  • A printed phone book holds every name. Easy to use - but heavy, and slow to print.
  • Turning the pages is fast: the pages already exist.
  • Now one person moves away. If every entry has a name (a key), you cross out one line.
  • If entries are only numbered by position, removing entry 1 shifts every number - so you reprint the whole book.

Example 1 - the normal list

app3.jsx is the orders table from Lesson 1.1, made into a reusable baseline:

  • It always loads orders-100000.json and keeps the first ?show=N orders, so every size uses the same data.
  • OrderList maps every order to an OrderRow. The key is order.id - or the array index with ?key=index.
  • useLayoutEffect without a dependency list runs after every commit: it marks “committed” and, after the next paint, “painted”. So both the first draw and later updates are timed.
  • window.removeFirst() is the test’s “delete” button: it removes the first order with setOrders((list) => list.slice(1)).
Example 1 - app3.jsx
// Lesson 2.1: the normal list - every order is a row, drawn with .map(). // ?show=1000 how many of the 100,000 orders to put in the list // ?key=index use the array index as the React key (default: order.id) import { useEffect, useLayoutEffect, useState } from "react"; import { createRoot } from "react-dom/client"; const params = new URLSearchParams(location.search); const show = Number(params.get("show") || 100000); const indexKeys = params.get("key") === "index"; function OrderRow({ order }) { return ( <tr> <td>{order.id}</td> <td>{order.customer}</td> <td>{order.city}</td> <td>{order.status}</td> <td>{order.total.toFixed(2)}</td> <td>{order.items.length}</td> </tr> ); } function OrderList({ orders }) { // After every commit: mark it, then mark again once the browser has painted. useLayoutEffect(() => { performance.mark("committed"); requestAnimationFrame(() => setTimeout(() => { performance.mark("painted"); window.painted = (window.painted || 0) + 1; }), ); }); return ( <table> <tbody> {orders.map((order, index) => ( <OrderRow key={indexKeys ? index : order.id} order={order} /> ))} </tbody> </table> ); } function App() { const [orders, setOrders] = useState(null); useEffect(() => { fetch("/orders-100000.json") .then((res) => res.json()) .then((data) => { performance.mark("parsed"); setOrders(data.slice(0, show)); }); // For the test: remove the first order, like a "delete" button would. window.removeFirst = () => { performance.mark("update-start"); setOrders((list) => list.slice(1)); }; }, []); return orders ? <OrderList orders={orders} /> : <p>Loading orders…</p>; } createRoot(document.getElementById("root")).render(<App />);

Example 2 - measuring the whole life of the list

run3.mjs opens the page in headless Chromium and measures four things:

  • Mount: from “parsed” to the first “painted” mark.
  • Memory and layout: Chrome’s own counters from the DevTools protocol (Performance.getMetrics) - DOM nodes, JS heap after a garbage collection, and total layout time - plus the renderer process’s private memory (RssAnon) from Linux.
  • Scrolling: 40 mouse-wheel turns of 1,000 px, 50 ms apart, while requestAnimationFrame records the time between frames.
  • One update: window.removeFirst(), timed from “update-start” to the next “painted”, with a MutationObserver counting every DOM change React makes.
Example 2 - run3.mjs
// Lesson 2.1: the normal list at 1,000 to 100,000 rows - mount, memory, scrolling, one update. // node run3.mjs [runs] import fs from "node:fs"; import http from "node:http"; import os from "node:os"; import path from "node:path"; import { chromium } from "playwright-core"; const RUNS = Number(process.argv[2] || 5); const exe = fs.globSync(os.homedir() + "/.cache/ms-playwright/chromium_headless_shell-*/*/chrome-headless-shell")[0]; const server = http .createServer((req, res) => { const file = path.join("public", new URL(req.url, "http://x").pathname); res.writeHead(200, { "content-type": file.endsWith(".json") ? "application/json" : file.endsWith(".js") ? "text/javascript" : "text/html" }); fs.createReadStream(file).pipe(res); }) .listen(0); const base = "http://127.0.0.1:" + server.address().port; const browser = await chromium.launch({ executablePath: exe, args: ["--enable-precise-memory-info"] }); const browserCdp = await browser.newBrowserCDPSession(); // Private memory (RssAnon) of the tab's renderer process, as Linux reports it async function rendererMB() { const { processInfo } = await browserCdp.send("SystemInfo.getProcessInfo"); let kb = 0; for (const p of processInfo.filter((x) => x.type === "renderer")) { kb += Number(fs.readFileSync("/proc/" + p.id + "/status", "utf8").match(/RssAnon:\s+(\d+)/)[1]); } return kb / 1024; } async function open(query) { const page = await browser.newPage({ viewport: { width: 1280, height: 800 } }); const cdp = await page.context().newCDPSession(page); await cdp.send("Performance.enable"); await page.goto(base + "/app3.html?" + query); await page.waitForFunction(() => window.painted >= 1, null, { timeout: 300_000, polling: 100 }); return { page, cdp }; } // Chrome's own counters for the tab: DOM nodes (text nodes too), JS heap, total layout time. // Garbage is collected first, so the heap holds only what the page still uses. async function metrics(cdp) { await cdp.send("HeapProfiler.collectGarbage"); const { metrics } = await cdp.send("Performance.getMetrics"); const m = Object.fromEntries(metrics.map((x) => [x.name, x.value])); return { nodes: m.Nodes, heapMB: m.JSHeapUsedSize / 2 ** 20, tabMB: await rendererMB(), layoutMs: m.LayoutDuration * 1000 }; } async function mountAndScroll(show) { const { page, cdp } = await open("show=" + show); const mount = await page.evaluate(() => performance.getEntriesByName("painted")[0].startTime - performance.getEntriesByName("parsed")[0].startTime); const m = await metrics(cdp); // Scroll: 40 turns of the mouse wheel, 1,000 px each, 50 ms apart - and record every frame await page.mouse.move(600, 400); await page.evaluate(() => { window.frameTimes = []; let last = performance.now(); const tick = (now) => { window.frameTimes.push(now - last); last = now; if (!window.stopFrames) requestAnimationFrame(tick); }; requestAnimationFrame(tick); }); for (let i = 0; i < 40; i++) { await page.mouse.wheel(0, 1000); await new Promise((r) => setTimeout(r, 50)); } const scroll = await page.evaluate(() => { window.stopFrames = true; const f = window.frameTimes.slice(1); return { frames: f.length, worstFrame: Math.max(...f), slowFrames: f.filter((t) => t > 50).length, scrolledTo: Math.round(scrollY) }; }); await page.close(); return { mount, ...m, ...scroll }; } async function removeFirst(show, key) { const { page } = await open("show=" + show + "&key=" + key); const r = await page.evaluate( () => new Promise((resolve) => { // Count every change React makes to the DOM for this one update let changes = 0; new MutationObserver((records) => (changes += records.length)).observe(document.body, { subtree: true, childList: true, characterData: true }); const before = window.painted; window.removeFirst(); const wait = () => { if (window.painted > before) { const t = (name) => performance.getEntriesByName(name).at(-1).startTime; resolve({ update: t("painted") - t("update-start"), domChanges: changes }); } else setTimeout(wait, 20); }; wait(); }), ); await page.close(); return r; } const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)]; const n = (v, d = 0) => v.toLocaleString("en-US", { maximumFractionDigits: d, minimumFractionDigits: d }); async function repeat(fn) { const runs = []; for (let i = 0; i < RUNS; i++) runs.push(await fn()); return Object.fromEntries(Object.keys(runs[0]).map((k) => [k, median(runs.map((r) => r[k]))])); } console.log("browser " + browser.version() + " | median of " + RUNS + " runs"); const results = { mount: {}, update: {} }; console.log("\nrows mount+paint DOM nodes JS heap tab memory layout total scroll: frames worst frame frames >50 ms"); for (const show of (process.env.SHOW || "1000,10000,50000,100000").split(",").map(Number)) { const m = (results.mount[show] = await repeat(() => mountAndScroll(show))); console.log( n(show).padStart(7) + n(m.mount).padStart(12) + " ms" + n(m.nodes).padStart(12) + n(m.heapMB).padStart(7) + " MB" + n(m.tabMB).padStart(10) + " MB" + n(m.layoutMs).padStart(12) + " ms" + n(m.frames).padStart(16) + n(m.worstFrame).padStart(10) + " ms" + n(m.slowFrames).padStart(14), ); } console.log("\nremove the first order: rows key update+paint DOM changes"); for (const show of (process.env.UPDATE || "10000,100000").split(",").map(Number).filter(Boolean)) { for (const key of ["id", "index"]) { const u = (results.update[show + "/" + key] = await repeat(() => removeFirst(show, key))); console.log(" ".repeat(25) + n(show).padStart(7) + " " + ("key=" + key).padEnd(10) + n(u.update).padStart(9) + " ms" + n(u.domChanges).padStart(14)); } } fs.writeFileSync("results3.json", JSON.stringify(results, null, 1)); await browser.close(); server.close();
node run3.mjs 5
browser 159.0.8154.6 | median of 5 runs rows mount+paint DOM nodes JS heap tab memory layout total scroll: frames worst frame frames >50 ms 1,000 111 ms 13,015 3 MB 52 MB 53 ms 159 17 ms 0 10,000 1,028 ms 130,015 18 MB 175 MB 586 ms 157 17 ms 0 50,000 5,139 ms 650,015 82 MB 698 MB 2,937 ms 149 33 ms 0 100,000 10,249 ms 1,300,015 162 MB 1,383 MB 6,349 ms 99 33 ms 0 remove the first order: rows key update+paint DOM changes 10,000 key=id 249 ms 1 10,000 key=index 857 ms 52,185 100,000 key=id 2,098 ms 1 100,000 key=index 8,475 ms 521,985

Reading the output: start-up and memory

  • Mount grows with the rows: 111 ms for 1,000, 1,028 ms for 10,000, 5,139 ms for 50,000 and 10,249 ms for 100,000.
  • Chrome counted 1,300,015 DOM nodes at 100,000 rows. That is 13 per row: 7 elements (one <tr>, six <td>) and 6 text nodes. Lesson 1.1 counted only elements.
  • Layout alone took 6,349 ms at 100,000 rows - more than half of the mount.
  • JS heap after garbage collection: 3 MB at 1,000 rows, 162 MB at 100,000. That is the orders plus React’s own record of every row.
  • Tab memory: 52 MB at 1,000 rows, 1,383 MB at 100,000. The DOM and layout data live here, outside the JS heap - so the JS heap alone hides most of the cost.

Tip: Every case first parses the full 100,000-order file, and the tab can keep some of that memory after garbage collection. So the small cases include a fixed share that is not the list - compare the growth between sizes, not single numbers.

Reading the output: scrolling

  • At 1,000 and 10,000 rows the 40 wheel turns gave 159 and 157 frames, and the worst frame took 17 ms - one frame time at 60 frames per second. Perfectly smooth.
  • At 50,000 rows: 149 frames, the worst 33 ms - a missed frame here and there, still smooth.
  • At 100,000 rows: only 99 frames in the same time - the browser drew fewer pictures - but none took over 50 ms; the worst took 33 ms.
  • Why so good? After the first layout, the browser scrolls by moving pictures of the page it has already drawn, mostly away from the main thread.
  • So the normal list does not hurt while you scroll. It hurts when it appears, and when it changes.

Trap: one small change, every row

Removing one order should be cheap. But setOrders() gives React a new array, so React renders OrderList again and visits every row to see what changed:

  • key={order.id}: React matches each row to the same order as before. One row is gone, so it makes 1 DOM change. But it still re-rendered 99,999 rows to find that out, and the browser laid the table out again: 2,098 ms at 100,000 rows.
  • key={index}: after the first order is removed, every order sits at a new index. Row 0 now shows order 2, row 1 shows order 3, and so on - React rewrites the text of almost every cell: 521,985 DOM changes and 8,475 ms.
  • At 10,000 rows it is the same story, ten times smaller: 249 ms with real keys, 857 ms with index keys.
  • Fix 1: always use a real id as the key. Fix 2 - fewer rows to visit at all - is what virtual scrolling and pagination do.
The same update with two different keys
<OrderRow key={order.id} order={order} /> // the order’s own id <OrderRow key={index} order={order} /> // its position in the array
Output (from node run3.mjs 5)
remove the first order: rows key update+paint DOM changes 10,000 key=id 249 ms 1 10,000 key=index 857 ms 52,185 100,000 key=id 2,098 ms 1 100,000 key=index 8,475 ms 521,985

Watch out: React does not warn about index keys - the list looks right either way. Only the cost (and, with inputs or state inside rows, wrong rows keeping old state) shows the problem.

The normal list at a glance

The normal list

Every item becomes a row.

orders.map((o) => <OrderRow key={o.id} order={o} />)
Good key

Stable and unique for the item.

key={order.id}
Risky key

Changes when items move or are removed.

key={index}
Chrome’s counters

Nodes, JSHeapUsedSize, LayoutDuration.

cdp.send("Performance.getMetrics")
Count DOM changes

Every change React makes.

new MutationObserver(cb).observe(document.body, { subtree: true, childList: true, characterData: true })

Try it yourself

The code does not change. Swap the content string and the program does something else entirely.

Remove the last order

“Change removeFirst() to remove the last order instead (list.slice(0, -1)). How many DOM changes does key={index} make now - and why?”

Add at the top

“Add a new order at the start of the list. Compare key={order.id} and key={index}.”

Simpler rows

“Show only id and customer in each row. How much do mount time and tab memory fall at 100,000 rows?”

Bigger window

“Run the scroll test with a 1920 x 1080 viewport. Does the worst frame at 100,000 rows change?”

What usually goes wrong

Using the index as key in a list that changes

Removing one order made 521,985 DOM changes with key={index}, against 1 with key={order.id}.

✗ <OrderRow key={index} order={order} />
✓ <OrderRow key={order.id} order={order} />
Reading only the JS heap

At 100,000 rows the JS heap was 162 MB, but the tab used 1,383 MB. The DOM lives outside the JS heap.

Testing with a short list

1,000 rows mount in 111 ms; the same code needs 10,249 ms for 100,000.

Thinking smooth scrolling means a fast list

Scrolling was mostly smooth even at 100,000 rows - mount and updates were the slow parts.

Best practices

  • Start with the normal list - it is the simplest correct code.
  • Use a stable id as the key, never the index for lists that change.
  • Measure at the largest size you really expect, not with test data of ten rows.
  • Watch tab memory and DOM nodes, not only the JS heap.
  • Keep a baseline script like run3.mjs, so later changes can be compared.

Practice

Write these yourself before opening anything. Getting them wrong first is most of how this sticks.

1.

Add an “update one total” test: change order 1’s total and time the update for 10,000 and 100,000 rows with key={order.id}. How many DOM changes does it make, and how long does it take?

Show hint

setOrders((list) => list.map((o, i) => (i === 0 ? { ...o, total: o.total + 1 } : o))) - and count mutations as removeFirst does.

2.

Find the largest list size on your own computer where mounting the normal list stays under 100 ms.

Coding challenge

Your baseline sheet

Make a one-page baseline for a list in one of your own apps, like the output of run3.mjs.

It should
  • Mount time, DOM nodes and memory at three list sizes.
  • Worst frame while scrolling.
  • The cost of one small update, with the key you use today.
  • A sentence on which number would hurt users first as the data grows.

Key points

  • The normal list keeps every item in the DOM: 13 nodes per order here, text nodes included.
  • Mount: 111 ms at 1,000 rows, 10,249 ms at 100,000.
  • Tab memory: 52 MB at 1,000 rows, 1,383 MB at 100,000.
  • Scrolling a drawn list was mostly smooth; updates were not.
  • Removing one of 100,000 orders: 2,098 ms with real keys, 8,475 ms with index keys.

Quick check before you move on

How many DOM nodes did Chrome count for 100,000 rows?
1,300,015 - 13 per row, text nodes included.
How long did the 100,000-row list take to mount?
10,249 ms.
How many DOM changes did removing the first order make with key={index} at 100,000 rows?
521,985.
And with key={order.id}?
1 - but the update still took 2,098 ms.

Interview questions

What problems does rendering a very long list in React cause?

Slow first render and layout, large DOM and memory use, and slow updates, because every change re-renders and reconciles all items and re-lays out the page. Scrolling an already-rendered list is usually fine. The fixes are windowing/virtualisation or pagination.

Why should you not use the array index as a key?

Keys tell React which item a row belongs to. When items are inserted, removed or reordered, index keys shift, so React updates or re-mounts many rows needlessly and can attach state to the wrong item. Use a stable unique id.

How would you measure memory used by a list?

JS heap (performance.memory or DevTools) only covers JavaScript objects; DOM and layout memory is outside it. Use the DevTools Memory and Performance panels, the Performance.getMetrics counters, or the renderer process memory, and compare at several list sizes.

Quiz

  1. 1.

    Why did removing one order with key={index} change almost every row?

  2. 2.

    Why was the update still slow with key={order.id}?

  3. 3.

    Why was scrolling smooth when mounting was so slow?

  4. 4.

    Why did tab memory grow much more than the JS heap?

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...