Blog>
Snippets

Optimizing Performance in Virtualized Lists

Illustrate best practices for optimizing performance in a virtualized list, including memoization techniques and efficient state updates.
import React, { useState, useCallback, useMemo } from 'react';
import { FixedSizeList as List } from 'react-window';

const MyVirtualizedList = ({ items }) => {
  const [itemList, setItemList] = useState(items);

  // Memoized row to prevent unnecessary re-renders
  const Row = useMemo(() => ({ index, style }) => (
    <div style={style} key={index}>
      {itemList[index].name}
    </div>
  ), [itemList]);

  return (
    <List
      height={500}
      itemCount={itemList.length}
      itemSize={35}
      width={'100%'}
    >
      {Row}
    </List>
  );
};
This code snippet demonstrates a basic implementation of a virtualized list using react-window. It uses useState to manage the list's state and useMemo to memoize each row, preventing unnecessary re-renders of list items that have not changed. The memoized Row component is dynamically passed the current index and style for efficient rendering.
const useVirtualizedData = (data) => {
  return useMemo(() => data.map(item => ({ ...item })), [data]);
};

const EnhancedVirtualizedList = ({ items }) => {
  const virtualizedItems = useVirtualizedData(items);

  return <MyVirtualizedList items={virtualizedItems} />;
};
In this part, a custom hook named useVirtualizedData is defined to memoize the transformation of the original dataset. This ensures the dataset passed to the virtualized list is stable across re-renders unless the original data changes. This technique reduces the work done during updates and keeps performance snappy.
const handleScroll = useCallback(({ target }) => {
  const nearBottom = target.scrollHeight - target.scrollTop === target.clientHeight;
  if (nearBottom) {
    // Code to load more items, e.g., from an API
  }
}, []);
This code snippet showcases the use of useCallback to create a memoized scroll event handler. It calculates whether the user has scrolled near the bottom of the list. When this condition is met, additional data can be fetched, e.g., from an API, to implement infinite scrolling in conjunction with virtualization.