FrontendPro

75Implement a virtualized list rendering 100,000 items efficiently

mediumAbout 45 minutesCodingreactperformancevirtualizationscrolling

Problem

Rendering 100,000 <div>s freezes the page. Build <VirtualList items={items} itemHeight={40} height={400} overscan={3} renderItem={(item, index) => …} /> that renders only the rows that are visible, plus a few extra (overscan) above and below.

  • The scroll container is a <div data-testid="viewport"> with the given height and overflow: auto.
  • Inside it, a spacer <div data-testid="spacer"> is items.length * itemHeight pixels tall, so the scrollbar looks right.
  • Each rendered row is absolutely positioned at top = index * itemHeight, has data-index={index}, and contains renderItem(item, index).

Requirements

  • With 100,000 items, only about height / itemHeight + 2 * overscan rows exist in the DOM.
  • Scrolling updates which rows are rendered.
  • Never render indexes below 0 or beyond the last item.
  • Rows must be keyed by index, so React reuses DOM nodes efficiently while scrolling.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Video walkthroughs

Stuck? Watch someone solve it, then try again on your own.

Let's Build a VIRTUALIZED LIST from Scratch in React.jsRaj talks tech on YouTubeOpen on YouTube
Implement virtual list in react from scratchKumar Amresh on YouTubeOpen on YouTube

Step-by-step

Keep scrollTop in state and update it in the viewport's onScroll handler from event.currentTarget.scrollTop.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever