virtual: Slow rendering performance on scroll

I’ve been using the last few versions of react-virtual and i love the hook based api. However, I am getting some poor performance on row rendering. It’s the classic empty and then flash to content on scroll. I thought perhaps this could be an issue with emotion (which i use for styling), however after stripping away all the emotion styles on the rows, it still performs quite slowly. I have broken everything up quite a bit and made sure that rerenders are localized only to components which have state changes. I’ve also played around with the overscan quite a bit, and can’t seem to find a setting which renders smoothly. For the record, I am also using this with react-table. I am wondering if I am using the keys incorrectly somehow, or if this is just expected behavior. Below I’ve included some code snippets and a video:

virtualized-table-row.js

import { Flex } from "@chakra-ui/react";
import { Fragment } from "react";

const VirtualizedTableRow = ({ virtualRow, row }) => (
  <Flex
    ref={virtualRow.measureRef}
    h={`${virtualRow.size}px`}
    bg={row.isSelected ? "indigo.50" : "white"}
    _hover={{
      bg: row.isSelected ? "indigo.100" : "gray.100",
    }}
    position="absolute"
    w="100%"
    top="0"
    left="0"
    alignItems="center"
    style={{ transform: `translateY(${virtualRow.start}px)` }}
    minWidth="min-content"
    zIndex="1"
    role="group"
  >
    {row.cells.map((cell) => (
      <Fragment key={cell.getCellProps().key}>{cell.render("Cell")}</Fragment>
    ))}
  </Flex>
);

export default VirtualizedTableRow;

virtualized-table-body.js

/* eslint-disable react/jsx-props-no-spreading */
import { Box, Center, Spinner } from "@chakra-ui/react";
import { useCallback, useEffect } from "react";
import { useVirtual } from "react-virtual";
import VirtualizedTableRow from "./virtualized-table-row";
import VirtualizedTableRows from "./virtualized-table-rows";

const VirtualizedTableBody = ({
  getTableBodyProps,
  prepareRow,
  rows,
  memoizedData,
  container,
  getNextPage = null,
  page,
  scrollYProgress,
  isLoading,
}) => {
  const rowVirtualizer = useVirtual({
    size: rows.length || 5,
    parentRef: container,
    estimateSize: useCallback(() => 42, []),
    overscan: 100,
    keyExtractor: (index) => rows[index]?.id,
    paddingEnd: getNextPage && page > 1 ? 50 : 0,
  });

  console.log("rerender");

  useEffect(
    () =>
      scrollYProgress.onChange((latest) => {
        if (latest === 1 && !isLoading) {
          getNextPage();
        }
      }),
    [getNextPage, isLoading, scrollYProgress]
  );

  return (
    <Box
      {...getTableBodyProps()}
      minWidth="min-content"
      h={`${rowVirtualizer.totalSize}px`}
      position="relative"
    >
      <VirtualizedTableRows
        rowVirtualizer={rowVirtualizer}
        rows={rows}
        memoizedData={memoizedData}
        prepareRow={prepareRow}
      />

      <Box position="absolute" h="50px" w="100%" bg="white" bottom="0">
        <Center h="100%">{isLoading && page > 1 && <Spinner />}</Center>
      </Box>
    </Box>
  );
};

export default VirtualizedTableBody;

https://user-images.githubusercontent.com/8886318/119013404-f13b5e00-b964-11eb-887e-0c479e764ef0.mp4

Thanks again!

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 19
  • Comments: 17 (1 by maintainers)

Most upvoted comments

I solved the issue by wrapping every item in React.memo. This seems to mitigate unnecessary rerendering on scroll.

Here is a full example for dynamically sized items:

function VirtualList({ data }: { data: ListItemType[] }) { r
    
    const virtualizer = useWindowVirtualizer({
        count: data.length,
        estimateSize: (i) => 1000, 
        overscan: 5,
    })

    const virtualItems = virtualizer.getVirtualItems()
      
    return (
        <div style={{
            position: 'relative',
            height: `${virtualizer.getTotalSize()}px`,
        }}>
            <div style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                transform: `translateY(${virtualItems[0]?.start ?? 0}px)`,
            }}>
                {virtualItems.map( (virtualItem) => ( 
                    <div key={virtualItem.key} 
                        ref={virtualizer.measureElement}
                        data-index={virtualItem.index}
                    >
                        <MemoizedListItem data={data[virtualItem.index]} />
                    </div>
                ))}
            </div>
        </div>
    )
}

const MemoizedListItem = React.memo(({ data }: { data: ListItemType[] }) => { 
    return (
        <div style={{paddingBottom: "30px"}}>
            <ListItem data={data} />
        </div>
    )
})

Probably not relevant anymore, but I had the same issue with Chakra Table.

When I switched out every Chakra component to a ‘normal’ html element it rendered the rows much much faster.

I’m experiencing the same. Trying to migrate our custom table component from react virtuoso to tanstack virtual, because tanstack virtual is much more flexible. Performance was perfect in react virtuoso, but with tanstack virtual it is something like in your video.

@justasdev tanstack virtual is not doing any performance optimization while scrolling, so on every scroll everything is re-rendered, hard to say what is happening without reading the code, but try to pin point what is slow.

@Torsteinws Good to hear that wrapping items in React.memo helped with the performance! Optimizing virtualized lists is definitely not a trivial task. Performance can be influenced by many factors beyond just code, like hardware capabilities and how quickly the browser can render elements. It’s all about finding the right balance for your specific use case, but every bit of optimization helps overall.

Let me know if you come across any other findings!

@jsbeckr This was spot on for me… Chakra made everything crazy slow. I guess I won’t the using a components library after all, neither MUI, Chakra nor the one from Microsoft… at least not for tables