Skip to content

Long Lists

The Course
•
20 min study

Each row in a list is cheap. Ten thousand of them aren't. This lab shows 10,000 logged study sessions in a scrolling box that's 256 pixels tall: room for 8 rows.

10,000 rows React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { Profiler, useState } from "react"; import WindowedList from "./WindowedList.jsx"; import { logRender } from "./logRender.js"; import { sessions } from "./sessions.js"; const ROW = 32; function Row({ session }) { return ( <div className="card" style={{ height: ROW - 4, padding: "0.2rem 0.6rem", boxSizing: "border-box" }}> #{session.id} {session.topic} <span className="muted">· {session.minutes} min</span> </div> ); } export default function App() { const [windowed, setWindowed] = useState(true); return ( <main> <h1>{sessions.length.toLocaleString("en")} sessions</h1> <label> <input type="checkbox" checked={windowed} onChange={(e) => setWindowed(e.target.checked)} /> Windowed list </label> <Profiler id="List" onRender={logRender}> {windowed ? ( <WindowedList items={sessions} rowHeight={ROW} height={256} renderRow={(s) => <Row session={s} />} /> ) : ( <div style={{ height: 256, overflowY: "auto" }}> <ul className="cards" style={{ gap: 0 }}> {sessions.map((s) => ( <li key={s.id} style={{ height: ROW }}><Row session={s} /></li> ))} </ul> </div> )} </Profiler> <p className="muted">Rows on the page: <span id="row-count">{windowed ? "a few" : "all"}</span></p> </main> ); } // Logs each render of a <Profiler> subtree: which one, why, and how long it took. export function logRender(id, phase, actualDuration) { console.log(`${id} ${phase}: ${actualDuration.toFixed(0)} ms`); } const topics = ["Reducers", "Context", "Refs", "Suspense", "Stores", "Profiling", "Testing"]; // 10,000 logged study sessions. export const sessions = Array.from({ length: 10000 }, (_, i) => ({ id: i + 1, topic: topics[i % topics.length], minutes: 10 + ((i * 7) % 50), })); import { useState } from "react"; // Renders only the rows that fit in view, plus a few either side. The rest of // the list is empty space with the right height, so the scrollbar is real. export default function WindowedList({ items, rowHeight, height, renderRow, overscan = 4 }) { const [scrollTop, setScrollTop] = useState(0); const first = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan); const last = Math.min(items.length, Math.ceil((scrollTop + height) / rowHeight) + overscan); const visible = items.slice(first, last); return ( <div style={{ height, overflowY: "auto" }} onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}> <ul className="cards" style={{ height: items.length * rowHeight, position: "relative", gap: 0 }}> {visible.map((item, i) => ( <li key={item.id} style={{ position: "absolute", top: (first + i) * rowHeight, height: rowHeight, left: 0, right: 0 }}> {renderRow(item)} </li> ))} </ul> </div> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Scroll the list, then untick Windowed list, and watch the console.

What you'll see

Windowed, the list mounts in a few milliseconds, and the page holds about a dozen rows however far you scroll. Unticked, React creates all 10,000 rows even though only 8 are visible, so List update takes longer. Record both durations on your device; exact numbers vary with hardware, browser and development mode. Compare the two versions rather than trying to reproduce someone else's time.

Windowing

WindowedList renders only the rows in view, plus a few either side so fast scrolling doesn't show gaps:

JavaScript
const first = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
const last = Math.min(items.length, Math.ceil((scrollTop + height) / rowHeight) + overscan);
  • An inner element has the full height, items.length * rowHeight, so the scrollbar is the right size and scrolling feels real.
  • Each visible row is positioned absolutely at index * rowHeight.
  • Scrolling updates scrollTop, and the window moves:
JSX
return (
  <div style={{ height, overflowY: "auto" }} onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}>
    <ul className="cards" style={{ height: items.length * rowHeight, position: "relative", gap: 0 }}>
      {visible.map((item, i) => (
        <li key={item.id} style={{ position: "absolute", top: (first + i) * rowHeight, height: rowHeight, left: 0, right: 0 }}>
          {renderRow(item)}
        </li>
      ))}
    </ul>
  </div>
);

The number of mounted rows now depends on the box's height, not the total number of items. Keeping, filtering and sorting the full data still costs time and memory, and browsers have limits on scrollable dimensions. Windowing makes rendering fewer rows cheaper; it doesn't make a huge data set free.

The price

  • Rows need a known height. Variable heights need measuring, which is harder; libraries such as TanStack Virtual handle it.
  • The browser's find-in-page can't see rows that aren't rendered, and neither can a screen reader's list navigation. For lists people search with the browser, consider pagination or "Load more" instead.
  • It's code to maintain. Below a few hundred simple rows, plain rendering is usually fine. Measure first.
Exercise

Jump to a session

Add a Go to session number box and a Go button above the list. Clicking Go with 5000 scrolls the windowed list so that session #5000 is the top row:

Text
#5000 Context · 53 min

Do it without rendering more rows: the page should still hold about a dozen. Disable Go when the list isn't windowed.

Your working space React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { Profiler, useState } from "react"; import WindowedList from "./WindowedList.jsx"; import { logRender } from "./logRender.js"; import { sessions } from "./sessions.js"; const ROW = 32; function Row({ session }) { return ( <div className="card" style={{ height: ROW - 4, padding: "0.2rem 0.6rem", boxSizing: "border-box" }}> #{session.id} {session.topic} <span className="muted">· {session.minutes} min</span> </div> ); } export default function App() { const [windowed, setWindowed] = useState(true); return ( <main> <h1>{sessions.length.toLocaleString("en")} sessions</h1> <label> <input type="checkbox" checked={windowed} onChange={(e) => setWindowed(e.target.checked)} /> Windowed list </label> <Profiler id="List" onRender={logRender}> {windowed ? ( <WindowedList items={sessions} rowHeight={ROW} height={256} renderRow={(s) => <Row session={s} />} /> ) : ( <div style={{ height: 256, overflowY: "auto" }}> <ul className="cards" style={{ gap: 0 }}> {sessions.map((s) => ( <li key={s.id} style={{ height: ROW }}><Row session={s} /></li> ))} </ul> </div> )} </Profiler> <p className="muted">Rows on the page: <span id="row-count">{windowed ? "a few" : "all"}</span></p> </main> ); } // Logs each render of a <Profiler> subtree: which one, why, and how long it took. export function logRender(id, phase, actualDuration) { console.log(`${id} ${phase}: ${actualDuration.toFixed(0)} ms`); } const topics = ["Reducers", "Context", "Refs", "Suspense", "Stores", "Profiling", "Testing"]; // 10,000 logged study sessions. export const sessions = Array.from({ length: 10000 }, (_, i) => ({ id: i + 1, topic: topics[i % topics.length], minutes: 10 + ((i * 7) % 50), })); import { useState } from "react"; // Renders only the rows that fit in view, plus a few either side. The rest of // the list is empty space with the right height, so the scrollbar is real. export default function WindowedList({ items, rowHeight, height, renderRow, overscan = 4 }) { const [scrollTop, setScrollTop] = useState(0); const first = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan); const last = Math.min(items.length, Math.ceil((scrollTop + height) / rowHeight) + overscan); const visible = items.slice(first, last); return ( <div style={{ height, overflowY: "auto" }} onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}> <ul className="cards" style={{ height: items.length * rowHeight, position: "relative", gap: 0 }}> {visible.map((item, i) => ( <li key={item.id} style={{ position: "absolute", top: (first + i) * rowHeight, height: rowHeight, left: 0, right: 0 }}> {renderRow(item)} </li> ))} </ul> </div> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Row 5000 isn't on the page, so there's no element to call scrollIntoView on: this is the find-in-page problem again. But you know exactly where it would be, from the same arithmetic WindowedList uses to place rows. Setting the box's scroll position fires its onScroll, and the window moves there by itself. The box belongs to WindowedList, so it should offer the parent a small way to ask for that, like Day 1's timer handle.

Hint 2: a first step

In WindowedList, give the scrolling <div> a ref, and accept a ref prop. Expose one method with useImperativeHandle, scrollToIndex(index), that only logs the index for now. In App, pass a ref to WindowedList and call the method from Go: the console should show 4999 for session 5000, because ids start at 1 and indexes at 0. Then make the method set the box's scrollTop. What position does row 4999 start at?

Show one solution

In WindowedList.jsx:

JSX
import { useImperativeHandle, useRef, useState } from "react";

export default function WindowedList({ items, rowHeight, height, renderRow, overscan = 4, ref }) {
  const [scrollTop, setScrollTop] = useState(0);
  const box = useRef(null);

  useImperativeHandle(ref, () => ({
    scrollToIndex(index) {
      box.current.scrollTop = index * rowHeight;
    },
  }), [rowHeight]);

  // ...first, last and visible as before
}

and ref={box} on the scrolling <div>. In App.jsx:

JSX
const listRef = useRef(null);
const [target, setTarget] = useState("5000");
JSX
<p>
  <label>
    Go to session <input type="number" min={1} max={sessions.length} value={target} onChange={(e) => setTarget(e.target.value)} />
  </label>{" "}
  <button onClick={() => listRef.current.scrollToIndex(Number(target) - 1)} disabled={!windowed}>Go</button>
</p>
JSX
<WindowedList ref={listRef} items={sessions} rowHeight={ROW} height={256} renderRow={(s) => <Row session={s} />} />

Import useRef in App.jsx. Row 4999 starts at 4999 × 32 = 159,968 pixels, so that's the scroll position. The browser fires scroll, WindowedList stores the new scrollTop, and the next render mounts sessions #4996 to #5011. The parent never touches the box or the row arithmetic: it only asks for an index.

Was this article helpful?

Your response is saved on this device.