Course contentsShow
← React
Lesson 2300 of 2,39650. Performance: Optimization TechniquesFree lesson

Scroll Position and Item Caching

Managing scroll restoration, caching item sizes for consistency, and handling dynamic content updates.

Scroll Position and Item Caching

What you'll learn: How to preserve scroll position across re-renders and cache measured item dimensions for smooth, consistent virtualized list behavior.

The Problem Virtualization Creates

When you virtualize a list, React unmounts items outside the viewport. If you navigate away and back, or if the list updates, you'll lose your scroll position. Worse, if items have variable heights, the virtualization library must measure each item's size the first time it renders—causing jumpy scrolling as dimensions are discovered.

Restoring Scroll Position

Think of scroll position like a bookmark: you need to save the page number before closing the book. Most virtualization libraries (like React Window) expose a scrollTo method and an onScroll callback:

const listRef = useRef();
const [scrollOffset, setScrollOffset] = useState(0);

const handleScroll = ({ scrollOffset }) => {
  setScrollOffset(scrollOffset);
};

// Restore on mount
useEffect(() => {
  listRef.current?.scrollTo(scrollOffset);
}, []);

Store scrollOffset in component state, URL params, or session storage depending on your UX needs.

Caching Item Sizes

For variable-height lists, measuring every item on every render kills performance. Libraries like React Window's VariableSizeList accept a itemSize function—but you must cache measurements:

const sizeMap = useRef({});

const getItemSize = (index) => {
  return sizeMap.current[index] || 50; // fallback height
};

const setItemSize = (index, size) => {
  sizeMap.current[index] = size;
  listRef.current?.resetAfterIndex(index);
};

When dynamic content updates (new data loads, text wraps differently), invalidate affected cache entries with resetAfterIndex() to trigger remeasurement.

Key Takeaway: Scroll restoration and item size caching are essential for production virtualized lists—without them, users experience jarring jumps and inconsistent scrolling behavior, especially with variable-height content.