javascript
37 lines · 8 steps
How a virtualized list works in React
Render only the rows currently on screen so a huge list stays fast to scroll.
Explained by
highlit
1import { useRef, useState, useCallback, useMemo } from 'react';
2
3export function VirtualList({ items, rowHeight = 40, height = 600, overscan = 5, renderRow }) {
4 const [scrollTop, setScrollTop] = useState(0);
5 const containerRef = useRef(null);
6
7 const handleScroll = useCallback((e) => {
8 setScrollTop(e.currentTarget.scrollTop);
9 }, []);
10
11 const { startIndex, endIndex, offsetY } = useMemo(() => {
12 const visibleCount = Math.ceil(height / rowHeight);
13 const start = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
14 const end = Math.min(items.length, start + visibleCount + overscan * 2);
15 return { startIndex: start, endIndex: end, offsetY: start * rowHeight };
16 }, [scrollTop, height, rowHeight, overscan, items.length]);
17
18 const visibleItems = items.slice(startIndex, endIndex);
19
20 return (
21 <div
22 ref={containerRef}
23 onScroll={handleScroll}
24 style={{ height, overflowY: 'auto', position: 'relative' }}
25 >
26 <div style={{ height: items.length * rowHeight }}>
27 <div style={{ transform: `translateY(${offsetY}px)` }}>
28 {visibleItems.map((item, i) => (
29 <div key={startIndex + i} style={{ height: rowHeight }}>
30 {renderRow(item, startIndex + i)}
31 </div>
32 ))}
33 </div>
34 </div>
35 </div>
36 );
37}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Rendering only the visible slice keeps DOM size constant no matter how many items exist.
- 2A full-height spacer preserves the real scrollbar while a translate offset positions the rendered window.
- 3Overscan renders a few extra rows beyond the viewport to hide blank flashes during fast scrolling.
Related explainers
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
7 steps
javascript
import { useState, useCallback, useRef } from 'react'; function LikeButton({ postId, initialLiked, initialCount }) { const [liked, setLiked] = useState(initialLiked);
Optimistic like button with React
optimistic-ui
abortcontroller
error-handling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-virtualized-list-works-in-react-explained-javascript-7304/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.