Virtualized List: 10,000 Rows, Twenty Nodes
Requirements
Work in src/App.tsx; treatPAYMENTS, the constants anduseRowNodeMeteras given. The starter renders all 10,000 rows and scrolls, while.rangeand Go are stubs; the four tasks make it fast without changing how the list looks.Task 1: render a window. Keep POOL_SIZE(20).rowelements inside.spacer:VISIBLE_ROWS(10) plusOVERSCAN(5) on each side, starting five rows above the first visible row and clamped so the pool stays inside the list (payments 1–20 at the top, 9,981–10,000 at the bottom). Keep the spacer's height and each row'stranslateYoffset as the starter writes them. Each row keepsrole="listitem",data-id,aria-posinset(its payment number),aria-setsize(10000), a.paymenttext such asPayment 1,001and its.amount.Task 2: set state in the viewport's scroll handler itself and render the rows in that same update. Do not batch it into requestAnimationFrameor defer the rows: the checks run in a frame that runs no animation frames, and they read the rows as soon as.rangechanges. The first visible row is the one at the top edge, unless less than half a pixel of it is left;.rangecounts ten rows from it,Showing 1,001–1,010 of 10,000, with en-US digit grouping and an en dash.Task 3: .go, the form's submit button, scrolls the list so the payment typed in.jumpis the first visible row (9,991 and up show the last page), sets the window in the same handler, and saysJumped to payment 4,821.in.jump-status. For anything but digits from 1 up (an empty field,0,-3,2.5,4821.0,1e3), leave the list where it is and sayEnter a whole payment number from 1 to 10,000.Task 4: recycle the row nodes. Scrolling must reuse the same twenty elements, so .row-meterkeeps reading20 row nodes created.Keep the viewport's role="list",aria-label="Payments"andtabIndex={0},ref={listRef}on.viewportandref={meterRef}on.row-meter, the viewport atVIEWPORT_HEIGHT, and the viewport'smin-widthin the workspace'sApp.css, which lets it scroll in the 1px-wide frame the checks run in.
What the checks look for
The checks find elements by .row, .row-meter, .row[data-id="1"] .payment, .row[data-id="1"] .amount, .row[data-id="20"], .row[data-id="21"], .range, .spacer, .viewport, .row[data-id="7"], .row[data-id="996"], .row[data-id="995"], .row[data-id="1015"], .row[data-id="1016"], .row[data-id="1001"] .payment, .row[data-id="1001"], .row[data-id="1001"] .amount, .row[data-id="1015"] .amount, .row[data-id="1"], .row[data-id="10000"], .row[data-id="9981"], .row[data-id="9980"], .jump, .go, .row[data-id="4821"] .payment, .row[data-id="4821"] .amount, .jump-status, .row[data-id="10000"] .amount. Keep these in your markup.
Expected behavior
At the top, payments 1–20 render, .rangereadsShowing 1–10 of 10,000, and payment 1 shows$357.61.Scrolled to 36,000px, .rangereadsShowing 1,001–1,010 of 10,000; payments 996 to 1,015 render attranslateY(35820px)totranslateY(36504px), and payment 1,001 shows$967.61.Scrolled 70px it reads Showing 2–11, and 216pxShowing 7–16with payments 2 to 21. At the bottom (359,640px) it readsShowing 9,991–10,000with payments 9,981 to 10,000.Jumping to 4821 shows Showing 4,821–4,830 of 10,000, payment 4,821 at$37.81andJumped to payment 4,821.; 9995 or 12000 show the last page andJumped to payment 9,991.; bad input leaves the list where it is and shows the message.Scrolling to the end and back leaves .row-meterat20 row nodes created.
Implementation notes
Everything the list shows can follow from one number: the first visible row. A key decides which DOM node a row lands in.
Solution idea
A virtual list is a function of one number. The scroll handler turns scrollTop into the first visible row, and from that row come a twenty-row pool (five rows of overscan above, ten visible, five below, clamped to the list), the range line and every offset. A spacer as tall as all 10,000 rows gives the browser its scroll range.
Public interview reports
These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.
- interview.tw: Binance frontend engineer interview, Taiwan, 2022
The fourth round of a 2022 Binance frontend loop asked how you would implement list recycling yourself. This task builds a list that recycles its rows; it is not the reported wording.
Reported in a public Binance interview account. Binance frontend interview questions
Solution
Overview
A virtual list is a function of one number. The scroll handler turns scrollTop into the first visible row, and from that row come a twenty-row pool (five rows of overscan above, ten visible, five below, clamped to the list), the range line and every offset. A spacer as tall as all 10,000 rows gives the browser its scroll range.
A jump writes scrollTop and sets the row in the same handler, because the scroll event it causes comes a frame later, and a status line says where it landed or why it did not move. Rows are keyed by their position in the pool, so twenty elements serve the whole list without being created, removed or reordered, and aria-setsize with aria-posinset keep the real size available to assistive technology.
Test cases
- The first window holds payments 1 to 20 inside a labelled, focusable list, with their offsets and a full-height spacer.
- Scrolling to payment 1,001 renders 996 to 1,015 at their own offsets with their own amounts.
- A partly hidden top row still counts as first; the top overscan and the last page keep twenty rows.
- Go moves the list to a payment and says so; 9,991 and up show the last page.
- Scrolling to the end and back reuses the same twenty row nodes.
- Go leaves the list where it is and says why for anything but a whole payment number.
One scroll position, a clamped pool, rows keyed by slot
Build it in the order of the tasks.
- Replace the full map with a pool:
start = clamp(firstVisible - OVERSCAN, 0, ITEM_COUNT - POOL_SIZE), then map the twenty indexes fromstart, keeping the spacer height and each row'stranslateY(index × ROW_HEIGHT). - Hold
firstVisible(a zero-based row index) in state and set it inonScrollwithfloor((scrollTop + 0.5) / ROW_HEIGHT), capped at index 9,990 so the last page stays full. The range line isfirstVisible + 1tofirstVisible + 10, formatted withIntl.NumberFormat('en-US'). - On submit, accept only digits from 1 up, write
(n - 1) × ROW_HEIGHT(capped at the last page) tolistRef.current.scrollTop, set the row from the position the browser applied, and put the result in therole="status"line; for anything else, leave the list and put the message there. - Change the key from the payment id to the row's position in the pool. Each of the twenty elements then always shows the same position, and React rewrites their text and offsets in place.
Follow-ups an interviewer asks
- Position keys or slot keys? Position keys rewrite all twenty rows on every step but never move an element; slot keys (
index % POOL_SIZE) rewrite only the rows that changed but make React reorder elements, one per row scrolling down and nineteen scrolling up. Either recycles; with twenty light rows the moves cost more than the text. - What breaks when rows are recycled? State inside a row (a text input, focus, an open menu) stays with the element and shows up on another payment after a scroll. Key by id when rows own state, or lift that state out by payment id.
- What if rows have different heights? Keep a prefix sum of measured heights and binary-search it for the first visible row; estimate unmeasured rows and correct the offsets as they are measured.
- How does a screen reader experience it? The viewport is a labelled, focusable list; screen readers that support
aria-posinsetannounce a row's position out of 10,000, and the status line announces where a jump landed.
Files
{
"name": "react-virtualized-list-recycling",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "18.x",
"react-dom": "18.x",
"react-scripts": "5.0.1"
},
"scripts": { "start": "react-scripts start" }
}
{
"compilerOptions": {
"jsx": "react-jsx",
"target": "ES2020",
"module": "ESNext",
"strict": true
}
}
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>React SDK • Payments</title></head><body><div id="root"></div></body></html>:root {
color-scheme: dark;
}
html,
body {
margin: 0;
height: 100%;
background: #020617;
font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
}
.main {
box-sizing: border-box;
min-height: 100vh;
background: #020617;
color: #e5e7eb;
display: grid;
grid-template-columns: minmax(0, 1fr);
place-items: center;
padding: 24px;
}
.card {
box-sizing: border-box;
width: 100%;
max-width: 560px;
background: #020617;
border-radius: 16px;
border: 1px solid #1f2937;
min-width: 0;
padding: 18px 18px 16px;
display: grid;
gap: 14px;
}
.header {
display: grid;
gap: 4px;
}
.title {
margin: 0;
font-size: 20px;
font-weight: 700;
}
.subtitle {
margin: 0;
font-size: 13px;
color: #9ca3af;
}
.jump-form {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.label {
font-size: 13px;
color: #9ca3af;
}
.jump {
width: 120px;
background: #0f172a;
color: #e5e7eb;
border: 1px solid #334155;
border-radius: 8px;
padding: 6px 8px;
font: inherit;
}
.go {
background: #1e293b;
color: #e5e7eb;
border: 1px solid #334155;
border-radius: 8px;
padding: 6px 12px;
font: inherit;
cursor: pointer;
}
.list-status {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 8px;
font-size: 13px;
color: #9ca3af;
}
.range {
margin: 0;
font-variant-numeric: tabular-nums;
}
.row-meter {
font-size: 12px;
color: #9ca3af;
}
.jump-status {
flex-basis: 100%;
margin: 0;
min-height: 18px;
font-size: 13px;
color: #93c5fd;
}
.viewport {
position: relative;
/* The checks run in a 1px-wide frame; without a width of its own the list has nothing to scroll there. */
min-width: 200px;
overscroll-behavior: contain;
overflow-y: auto;
border: 1px solid #1f2937;
border-radius: 10px;
}
.viewport:focus-visible {
outline: 2px solid #93c5fd;
outline-offset: 2px;
}
.spacer {
position: relative;
}
.row {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 36px;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 0 12px;
border-bottom: 1px solid #1f2937;
font-size: 14px;
}
.amount {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-variant-numeric: tabular-nums;
color: #86efac;
}
import React, { useEffect, useRef, useState } from 'react';
import './App.css';
export interface Payment {
id: number;
amountCents: number;
}
export const ITEM_COUNT = 10000;
export const ROW_HEIGHT = 36;
export const VIEWPORT_HEIGHT = 360;
export const VISIBLE_ROWS = VIEWPORT_HEIGHT / ROW_HEIGHT;
export const OVERSCAN = 5;
export const POOL_SIZE = VISIBLE_ROWS + 2 * OVERSCAN;
/** Ten thousand payments, the same on every run. */
export const PAYMENTS: Payment[] = Array.from({ length: ITEM_COUNT }, (_, index) => ({
id: index + 1,
amountCents: ((index + 1) * 2654435761) % 100000,
}));
const numberFormat = new Intl.NumberFormat('en-US');
const moneyFormat = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
export const formatNumber = (value: number) => numberFormat.format(value);
export const formatMoney = (cents: number) => moneyFormat.format(cents / 100);
/**
* Given: counts the row nodes ever created inside the list, so the recycling check can read it. Keep
* `ref={listRef}` on `.viewport` and `ref={meterRef}` on `.row-meter`.
*/
function useRowNodeMeter() {
const listRef = useRef<HTMLDivElement>(null);
const meterRef = useRef<HTMLSpanElement>(null);
useEffect(() => {
const list = listRef.current;
const meter = meterRef.current;
if (!list || !meter) return;
const seen = new WeakSet<Element>();
let created = 0;
const note = (node: Node) => {
if (!(node instanceof Element)) return;
const rows = node.matches('.row') ? [node] : Array.from(node.querySelectorAll('.row'));
for (const row of rows) {
if (seen.has(row)) continue;
seen.add(row);
created += 1;
}
};
const show = () => {
meter.textContent = `${formatNumber(created)} row nodes created`;
};
note(list);
show();
const observer = new MutationObserver((records) => {
for (const record of records) record.addedNodes.forEach(note);
show();
});
observer.observe(list, { childList: true, subtree: true });
return () => observer.disconnect();
}, []);
return { listRef, meterRef };
}
const LAST_FIRST_ROW = ITEM_COUNT - VISIBLE_ROWS;
/**
* The row at the top edge of the viewport, partly scrolled out or not. A row with less than half a pixel left on
* screen counts as scrolled out: a zoomed browser can report 173519.4px for a jump to 173520px.
*/
function rowAt(scrollTop: number) {
return Math.min(Math.max(Math.floor((scrollTop + 0.5) / ROW_HEIGHT), 0), LAST_FIRST_ROW);
}
export default function App() {
const { listRef, meterRef } = useRowNodeMeter();
// Only the first visible row is state: a scroll that stays inside one row sets the same number, and React bails
// out without committing anything.
const [firstVisible, setFirstVisible] = useState(0);
const [jumpText, setJumpText] = useState('');
const [jumpStatus, setJumpStatus] = useState('');
const start = Math.min(Math.max(firstVisible - OVERSCAN, 0), ITEM_COUNT - POOL_SIZE);
const indexes = Array.from({ length: POOL_SIZE }, (_, offset) => start + offset);
// A jump moves the list and sets the window in the same handler, from the position the browser applied.
const handleJump = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const list = listRef.current;
const target = Number(jumpText.trim());
if (!/^\d+$/.test(jumpText.trim()) || target < 1 || !list) {
setJumpStatus(`Enter a whole payment number from 1 to ${formatNumber(ITEM_COUNT)}.`);
return;
}
list.scrollTop = Math.min(target - 1, LAST_FIRST_ROW) * ROW_HEIGHT;
const row = rowAt(list.scrollTop);
setFirstVisible(row);
setJumpStatus(`Jumped to payment ${formatNumber(row + 1)}.`);
};
return (
<main className="main">
<section className="card">
<header className="header">
<h1 className="title">Payments (Solution)</h1>
<p className="subtitle">Ten thousand rows. Draw the twenty that matter.</p>
</header>
<form className="jump-form" onSubmit={handleJump}>
<label className="label" htmlFor="jump">Jump to payment</label>
<input
id="jump"
className="jump"
type="text"
inputMode="numeric"
autoComplete="off"
value={jumpText}
onChange={(event) => setJumpText(event.target.value)}
/>
<button type="submit" className="go">Go</button>
<p className="jump-status" role="status">{jumpStatus}</p>
</form>
<div className="list-status">
<p className="range">
Showing {formatNumber(firstVisible + 1)}–{formatNumber(firstVisible + VISIBLE_ROWS)} of {formatNumber(ITEM_COUNT)}
</p>
<span className="row-meter" ref={meterRef} />
</div>
<div
className="viewport"
ref={listRef}
role="list"
aria-label="Payments"
tabIndex={0}
style={{ height: VIEWPORT_HEIGHT }}
onScroll={(event) => setFirstVisible(rowAt(event.currentTarget.scrollTop))}
>
<div className="spacer" style={{ height: ITEM_COUNT * ROW_HEIGHT }}>
{indexes.map((index, offset) => {
const payment = PAYMENTS[index];
// Keyed by position in the pool: element 0 always shows the pool's first payment, so scrolling
// rewrites the twenty elements in place and never creates, removes or reorders one.
return (
<div
key={offset}
className="row"
role="listitem"
aria-posinset={payment.id}
aria-setsize={ITEM_COUNT}
data-id={payment.id}
style={{ transform: `translateY(${index * ROW_HEIGHT}px)` }}
>
<span className="payment">Payment {formatNumber(payment.id)}</span>
<span className="amount">{formatMoney(payment.amountCents)}</span>
</div>
);
})}
</div>
</div>
</section>
</main>
);
}
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
createRoot(document.getElementById('root')!).render(<App />);
Common mistakes on this challenge
Keep the first visible row in state, and key rows by their place in the pool
The scrolling and jump checks read one window built from the first visible row, and they read it as soon as the range line changes. The recycling check counts the row elements ever created, so a key per payment adds one for every row that scrolls in. In onScroll, setfirstVisibletofloor((scrollTop + 0.5) / ROW_HEIGHT)capped at index 9,990, directly rather than throughrequestAnimationFrame, and derivestart = clamp(firstVisible - OVERSCAN, 0, ITEM_COUNT - POOL_SIZE).On Go, accept only digits from 1 up, write the capped position to listRef.current.scrollTop, set the row from it, and report the result or the error in.jump-status.Key each row by its position in the pool ( offset), so the same twenty elements are rewritten instead of new ones being created.
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.