Blog>
Snippets

Utilizing Memoization with TanStack Virtual Rows

Exemplify the use of React.memo to wrap a component rendered by TanStack Virtual for preventing unnecessary re-renders of list items, thereby enhancing performance, especially in longer lists.
const VirtualRow = React.memo(({ index, data }) => {
  // This component represents a single row in the virtual list.
  // React.memo prevents unnecessary re-renders unless index or data changes.
  return (
    <div style={{ height: '50px', display: 'flex', alignItems: 'center' }}>
      {data[index]}
    </div>
  );
}, areEqual);
This code snippet defines a VirtualRow component wrapped with React.memo to optimize performance by preventing unnecessary re-renders of rows in a virtual list unless specific props change (in this case, index or data). 'areEqual' is a custom comparison function that can be provided for deeper comparisons, not included in this example.
// Assuming the presence of an `areEqual` function for deep comparison
function areEqual(prevProps, nextProps) {
  // Return true if passing nextProps to render would return
  // the same result as passing prevProps, otherwise return false
  return prevProps.index === nextProps.index && prevProps.data === nextProps.data;
}
This code defines an 'areEqual' function used for deep comparison of props in React.memo. It helps in determining if the VirtualRow component should re-render or not, by comparing the current and next props. This is an example of customization for memoization logic.