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 givenheightandoverflow: auto. - Inside it, a spacer
<div data-testid="spacer">isitems.length * itemHeightpixels tall, so the scrollbar looks right. - Each rendered row is absolutely positioned at
top = index * itemHeight, hasdata-index={index}, and containsrenderItem(item, index).
Requirements
- With 100,000 items, only about
height / itemHeight + 2 * overscanrows 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.
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.