Blog>
Snippets

Optimizing Large Lists Rendering

Showcase advanced techniques for optimizing the rendering of large lists in an infinite scroll context, using useMemo and useCallback to minimize re-renders and ensure smooth performance.
const ListItem = React.memo(({ item }) => (
  // Render your list item here
  <div>{item.name}</div>
));
Defines a memoized list item to prevent unnecessary re-renders of items that have not changed.
const fetchItems = async (startIndex, limit) => {
  // Fetch your data here
  return fetchedItems;
};
Asynchronously fetches a batch of items from your data source, starting from a specified index.
const useInfiniteScroll = (loadItems) => {
  const [items, setItems] = useState([]);
  useEffect(() => {
    const handleScroll = async () => {
      // Logic to determine when to load more items
      if (window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight) {
        const newItems = await loadItems(items.length, 10);
        setItems((prevItems) => [...prevItems, ...newItems]);
      }
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [loadItems, items]);
  return items;
};
A custom hook that listens for scroll events to load more items when the user scrolls to the bottom of the page. It uses an asynchronous function to fetch new items and appends them to the current list.
const VirtualList = ({ initialItems }) => {
  const loadMoreItems = useCallback(async (startIndex, limit) => {
    // Wrap your fetchItems call or any custom logic here
    return await fetchItems(startIndex, limit);
  }, []);

  const items = useInfiniteScroll(loadMoreItems);

  return (
    <div>
      {items.map((item, index) => (
        <ListItem key={index} item={item} />
      ))}
    </div>
  );
};
The main component that renders the virtual list. It incorporates useInfiniteScroll to handle infinite scrolling and utilizes useCallback to wrap fetch logic, ensuring the function remains consistent between renders.