Using react-window
When dealing with massive list data, rendering all DOM elements at once will inevitably degrade web performance. To optimize this, virtual lists can be used. The principle is that the program still maintains the complete list, but actually only renders a portion. As scrolling occurs, the program dynamically switches the rendered portion. This approach is fast enough and pre-renders additional content, making it virtually imperceptible to users. In the React ecosystem, you can choose to use
react-window
. Here’s how to use it.
Usage
Here’s the code directly:
<FixedSizeList height={430}
itemCount={logs.length}
itemSize={100}
width={'100%'}
className={'txlogs-vtable'}>
{
Row(logs)
}
</FixedSizeList>
const Row = (logs: TxLog[]) => memo(({ index, style }: { index: number; style: CSSProperties }) => {
const item = logs[index];
return <div key={index} style={style}>
<div className={'txlogs-item'}>
<div className={'flex meta-layout'}>
<div className={'datetime'}>
{
formatDate(new Date(item.timestamp * 1000))
}
</div>
</div>
</div>;
});
The above is a basic usage example. For complete parameter support, refer to the official documentation or the repo’s d.ts definition file.
Notes
- For vertical scrolling, the height of each row must be fixed.
- For each row,
the style parameter must be passed to the row component
, otherwise scrolling will have errors/flickering. This is because the style uses absolute positioning to determine the position of each row element within the entire scroll container.
Extensions
- For example, the antd-react component library’s table component uses react-window for virtual list support.
Final Thoughts
For displaying large datasets, infinite scrolling is one solution. Actually, adjustments can be made in functional design to avoid this, such as pagination. So, technology just serves product design - choose solutions flexibly.