Middle
Regarding tables — have you worked with complex long tables with virtualization, where only what is visible on the screen is rendered?
sobes.tech AI
Answer from AI
Yes, I have worked with large tables where virtualization was used to optimize rendering. The idea is to only include in the DOM the rows and columns that are visible to the user at the moment, while the rest are not rendered, which significantly improves performance.
Typically, this involves:
- Tracking the size of the visible area and scroll position.
- Calculating which rows and columns should be displayed.
- Rendering only these elements, while the others are virtually hidden.
Popular libraries with virtualization include:
- react-window
- react-virtualized
An example of simple virtualization for rows in React:
import React, { useState, useRef, useEffect } from 'react';
const rowHeight = 30;
const totalRows = 10000;
function VirtualizedTable() {
const [scrollTop, setScrollTop] = useState(0);
const viewportHeight = 300;
const startIndex = Math.floor(scrollTop / rowHeight);
const visibleCount = Math.ceil(viewportHeight / rowHeight);
const visibleRows = [];
for (let i = startIndex; i < startIndex + visibleCount; i++) {
if (i >= totalRows) break;
visibleRows.push(i);
}
return (
<div
style={{ height: viewportHeight, overflowY: 'auto', position: 'relative' }}
onScroll={e => setScrollTop(e.currentTarget.scrollTop)}
>
<div style={{ height: totalRows * rowHeight, position: 'relative' }}>
{visibleRows.map(i => (
<div
key={i}
style={{
position: 'absolute',
top: i * rowHeight,
height: rowHeight,
left: 0,
right: 0,
borderBottom: '1px solid #ccc',
boxSizing: 'border-box',
}}
>
Row {i}
</div>
))}
</div>
</div>
);
}
export default VirtualizedTable;
This approach allows working efficiently with large volumes of data without lag.