Skip to main content

Virtualization in React JS

· 2 min read
Juan Emilio Rivero

When our App contains lists or tables with a large number of elements, the performance will be affected due to loading all these elements into the DOM. Virtualization is a technique to improve the performance of WebApps that need to display large volumes of data, either in the form of lists or tables. The logic of Virtualization consists of rendering only the elements that are currently in the user's viewport. This serves to improve the initial load of the App, resulting in a better UX.

Virtualization in React JS

To create virtualized lists or tables in React JS, we use the 'react-window' library. This library provides us with components that work as wrappers to which we pass the elements of the list/table as children. 'react-window' provides basic utilities for virtualization. For more advanced implementations, such as Infinite Scroll, it should be complemented with the 'react-window-infinite-loader' library. Or if you want a container with dynamic dimensions, it should be complemented with the 'react-virtualized-auto-sizer' library.

How to Implement Virtualization

In this section, I will show a very basic example of virtualization. It will be just a demonstration with a list of 1000 elements.

The step-by-step process would be:

  • Install the library using the command npm install react-window.
  • Import the <FixedSizeList/>component.
  • Determine the width and height of the <FixedSizeList/> container.
  • <FixedSizeList/> takes props height, width, itemCount, and itemSize:
    • height: Height of the list, must match its container.
    • width: Width of the list, must match its container.
    • itemCount: Number of elements in the list.
    • itemSize: Approximate height of the elements to render.
  • Create the <Row/> component, which takes index and style as props (style is passed because each row must have a position: absolute and a translate of X number of pixels, depending on the item's height. The - index is needed to display the array position of the data).
  • Render the <Row/> component directly within <FixedSizeList/>.
  • Inspect the console and see the number of elements inside the container.

Conclusion

Virtualization is a powerful technique for improving performance, although it shouldn't necessarily be the first option. Initially, it's essential to review the rendering cost of components and try to reduce it as much as possible, either by further componentizing or by attempting to localize the state as much as possible.