React Virtualized. Part 1. Introduction
React is known for its efficiency, yet managing extensive lists and grids can challenge its performance. This post explores React Virtualization, a technique designed for rendering large lists and grids more efficiently. We’ll delve into React Virtualized, understanding how it optimizes rendering for significant data structures.
What is React Virtualized?
It is an open-source library which provides you many components in order to window some of your application List, Grid etc.As a developer, you do not want to reinvent the wheel. React-virtualized is a stable and maintained library. Its community is large and as it is open-source, many modules and extensions are already available in order to window a maximum of elements. Furthermore, it offers lots of functionalities and customization that you would not even think about.
How React Virtualized Work?
React Virtualized optimizes rendering for large lists and grids by selectively displaying content within the visible area of the screen, ensuring that only the items visible to the user are rendered. It achieves this through a windowing mechanism, creating a ‘window’ that contains the visible content. As users scroll through the list or grid, React Virtualized dynamically adjusts this ‘window’ to manage what’s displayed.
This library intelligently handles the rendering of components by unmounting those that have scrolled out of view and seamlessly mounting new components that enter the visible area. By efficiently managing component rendering based on user interaction, React Virtualized significantly reduces the number of elements handled by React, ensuring optimal performance when dealing with extensive datasets.
Components in React Virtualized
The main concept behind virtual rendering is rendering only what is visible.There are one thousand data in the app, but it only shows around ten at any moment (the ones that fit on the screen), until you scroll to show more.So it makes sense to load only the elements that are visible and unload them when they are not by replacing them with new ones.
React-virtualized implements virtual rendering with a set of components that basically work in the following way:
- They calculate which items are visible inside the area where the list is displayed.
- They use a container with relative positioning to absolute position the children elements inside of it by controlling its top, left, width and height style properties.
There are five main components:
- Grid. It renders tabular data along the vertical and horizontal axes.
- List. It renders a list of elements using a Grid component internally.
- Table. It renders a table with a fixed header and vertically scrollable body content. It also uses a Grid component internally.
- Masonry. It renders dynamically-sized, user-positioned cells with vertical scrolling support.
- Collection. It renders arbitrarily positioned and overlapping data.
These components extend from React.PureComponent, which means that when comparing objects, it only compares their references, to increase performance.
Higher Order Components in React Virtualized
Now that we’ve explored the primary components in React Virtualized, let’s also delve into the Higher Order Components (HOCs) available within React Virtualized. But first, what exactly are Higher Order Components?
Higher Order Components, often referred to as HOCs, are essentially components that take another component as input and produce a new component as output based on the provided component.
Get Onix React’s stories in your inbox
Join Medium for free to get updates from this writer.
The benefit of HOCs lies in their ability to encapsulate logic without modifying the component passed as an argument. This eliminates the need to duplicate or rewrite logic within the passed component.
- ArrowKeyStepper. Can be used to decorate another component so it can respond to arrow-key events.
- AutoSizer. Can be used to automatically adjust the width and height of another component.
- CellMeasurer. Can be used automatically measure a cell’s content by temporarily rendering it in a way that is not visible to the user.
- ColumnSizer. Can be used to calculate column widths for Grid cells.
- InfiniteLoader. Can be used to manage the fetching of data when users scroll through a List, Table, or Grid.
- MultiGrid. Can be used to decorate a Grid component so as to add fixed columns and/or rows.
- ScrollSync. Can be used to synchronize scrolling between two or more components.
- WindowScroller. Can be used to enable a Table or List component to be scrolled based on the window’s scroll positions.
Dependencies
React Virtualized has very few dependencies and most are managed by NPM automatically. However the following peer dependencies must be specified by your project in order to avoid version conflicts: react, react-dom. NPM will not automatically install these for you but it will show you a warning message with instructions on how to install them.
Let’s explore using the List component to efficiently display a large list of items. We’ll leverage virtualization techniques to boost performance and handle substantial amounts of data effectively. Ready to start?
Virtualizing a list
In this example, we’re leveraging the react-virtualized library to efficiently render a large list in a React application. The goal is to dynamically display 5000 items while optimizing performance by rendering only the items that are currently visible in the user’s viewport. Let’s break down the code and its functionality:
Data Generation: Start by generating a list of 5000 items, each with a unique ID, the name ‘John Doe,’ a random image sourced from Lorem Picsum, and a Lorem Ipsum text snippet. This simulated dataset is created for demonstration purposes.
import React from 'react';
import { loremIpsum } from 'lorem-ipsum';
import { List } from 'react-virtualized';
import './App.css';
const rowCount = 5000;
const listHeight = 400;
const rowHeight = 50;
const rowWidth = 700;
const list = Array(rowCount).fill().map((val, idx) => {
const randomImageId = Math.floor(Math.random() * 1000);
return {
id: idx,
name: 'John Doe',
image: `https://picsum.photos/40/40?image=${randomImageId}`,
text: loremIpsum({
count: 1,
units: 'sentences',
sentenceLowerBound: 4,
sentenceUpperBound: 8
})
};
});List Rendering: The List component from react-virtualized is used to render the virtualized list. It takes parameters such as width, height, rowHeight, rowRenderer, rowCount, and overscanRowCount. The rowRenderer function defines the structure of each row, receiving properties like index, key, and style to optimize rendering.
const renderRow = ({ index, key, style }) => (
<div key={key} style={style} className="row">
<div className="image">
<img src={list[index].image} alt="" />
</div>
<div className="content">
<div>{list[index].name}</div>
<div>{list[index].text}</div>
</div>
</div>
);
const App = () => (
<div className="App">
<div className="list">
<List
width={rowWidth}
height={listHeight}
rowHeight={rowHeight}
rowRenderer={renderRow}
rowCount={list.length}
overscanRowCount={3}
/>
</div>
</div>
);
export default App;Styling: Styling definitions in src/App.css enhance the visual presentation of the list. Each row has a border, is left-aligned, and includes a margin for better spacing. The image and content sections are styled accordingly.
.App {
text-align: center;
}
.list {
padding: 10px;
}
.row {
border-bottom: 1px solid #ebeced;
text-align: left;
margin: 5px 0;
display: flex;
align-items: center;
}
.image {
margin-right: 10px;
}
.content {
padding: 10px;
}This example demonstrates the power of virtualization in handling large datasets, ensuring optimal performance by rendering only the visible items. The styling ensures a clean and organized display of the list, making it a practical solution for web applications dealing with extensive data.
Conclusion
This article serves as an introduction to leveraging react-virtualized for optimizing application performance when dealing with extensive data. It offers a starting point for understanding its capabilities in rendering large datasets efficiently. Additionally, in this post, we’ve showcased only one of the five main components. In forthcoming posts, we’ll delve into detail about other components and explore further capabilities of React Virtualized.









