React Window
Overview
React Window is a node library that helps us optimize the web application by allowing us to render only a part of a huge data set, that is just enough to fill the viewport. This technique is known as windowing, as the user scrolls the text data gets loaded and the data or DOM that exits the "window" are recycled or replaced by these new ones. It reduces the amount of time and work required during the initial rendering of the web page.
Problems With Large DOM Size
First of all, what do we even mean by “Large DOM Size”? It means having a lot of individual or nested DOM elements or HTML tags.
There are often cases when we have a huge data set in the form of a list that needs to be rendered. A very basic and highly unoptimized approach will be to render the entire list at the time of loading of the page. This not only increases the DOM size but also increases the time taken to load the web page, this increases the performance budget resulting in a very slow website with jerky or slow scrolling. Apart from these, the UI can even fail to load in the worst case!
In this world of technology, the best developers target optimizing things and making them fast. Rendering the entire list of 1000 elements is not needed when our screen can only fit 10 of them! So why to degrade the performance by doing so, right?
What is Virtualization or Windowing in React?
Virtualization, also known as “Windowing” is a concept where we render only a part of a big data set such that it is big enough to fill the viewing window of the user. This provides us with the benefits of pagination along with infinite scrolling. We all can agree on the fact that infinite scrolling is much better UX compared to pagination where we need to click a button to move to the next page!
Virtualization or windowing increases the performance of the web page since we don’t have to render all the data at once which is of course time taking and results in jerky scrolling.
To virtualize a list, we pre-calculate the overall height of our list by multiplying the count of our list items by the dimensions of the provided list items.
Then, we arrange the elements such that the user would browse through a list. Because individual items may be added or deleted without impacting other items or forcing them to reflow (i.e., the process of recalculating an element's location on the page), accurately positioning our elements is essential to the efficiency of virtualization.
What is React Window?
React Window or react-window is a small third-party library that makes virtualization or windowing easy for us to implement. There are several base APIs in react-window that we can use for virtualizing different types of lists and tables.
Installation of react-window
Let’s take a quick look at how we can install this React Window library.
You might have already guessed since it is a node library so we will be using our good NPM.
Installation of list-generating Library
Since we will be learning this library so we need a HUGE list of data! And for that, we will be using another node library called faker. Let’s install that now.
Why is React Window Useful?
React Window or react-window library allows us to easily implement the concepts of Virtualization or Windowing using its APIs. As the user scrolls down the list, DOM nodes that leave the "window" are recycled or quickly replaced with fresh components. This maintains the proportion of all rendered items to the window's size.
Using React Window to Virtualize Large Lists
There are quite a few ways of using React Window or the react-window library for virtualizing large lists:
- Using Fixed Sized List
- Using Variably Sized List
- Using Grids
- Applying Lazy Loading on Scroll
- Overscanning
Let’s take a look at each of them and understand how and when to use them with examples.
When to Use Fixed Sized List?
In case we have a long, one-dimensional list of equally sized items, then we use FixedSizedList Components. Let’s take a look at the code now.
To adjust the size of the items in the list, the FixedSizeList component receives a height, width, and itemSize parameter.
- FixedSizeList receives a function that renders the rows as a child. Utilizing the index parameter, information on the specific object may be obtained (items[index]).
- The row rendering method additionally accepts a style argument, which must be connected to the row element. The style argument is what positions list items absolutely with their height and width values assigned inline.
Caution: Avoid using an external CSS file to set the height and width of the list or the list item. Due to the inline application of these style characteristics, they would be disregarded.
When to Use Variable Sized List?
To render a list of items with various sizes, i.e. may be of different lengths of text or different sizes of images, we use the VariableSizeList component. This component functions similarly to a fixed-size list but anticipates a function rather than a particular value for the itemSize argument.
As we can see, the size of each item is determined using the length of the lorem ipsum sentences
Explanation
In this example, the row heights are randomized by the item size function that was supplied to the itemSize prop. In a web application, the sizes of each item should be determined by some logic, here we have used the length as a parameter for size. These sizes should ideally be computed using data or retrieved via an API.
Note: By utilizing a layout="horizontal" parameter, the FixedSizeList and VariableSizeList components both support horizontal lists. To view an example, check the documentation.
Using Grids
In addition to the lists as we have seen in the above two use cases, react-window supports virtualizing multi-dimensional grids or lists. In this case, when the user scrolls both horizontally and vertically, the "window" of viewable content changes. This is a two-dimensional extension of the earlier lists!
Explanation
As we can see in the output below, we can scroll both horizontally and vertically. This is how we can apply the concept of windowing to a two-dimensional data set.
Similarly, depending on whether the size of certain list items may fluctuate, either FixedSizeGrid or VariableSizeGrid components can be utilized.
- The API is essentially the same for FixedSizeGrid, except item counts, heights, and widths must be given for both columns and rows.
- Column widths and row heights for VariableSizeGrid may both be modified by supplying functions rather than values to the corresponding props.
You can take a look at the several virtualized grid examples in the documentation.
Note: react-window offers additional features like the ability to scroll to a specific item or the ability to display an indicator while the user is scrolling in addition to the fundamental building blocks needed to build effective lists and grids. Examples of this are provided in the documentation.
Applying Lazy Loading on Scroll
Many websites boost speed by delaying the loading and rendering of extensive lists of content until after the user has scrolled down. This method, often known as "infinite loading," expands the list of DOM nodes when the user scrolls past a predetermined point toward the end. Although this is preferable to loading every item on a list at once, once the user has scrolled past that many, millions of row entries still end up populating the DOM. This can result in an extremely large DOM size, which starts to affect performance by slowing down DOM changes and style computations.
The image below might help summarize what is mentioned above.
Although react-window is a fantastic tool, adding an endless loading list can make it a little verbose. A component called react-simple-infinite-loading manages code complexity on your behalf. It serves as a wrapper for the following three libraries:
- Large lists may be displayed well using react-window. It reuses nodes and only builds components for the items that are visible.
- A HOC called react-window-infinite-loader loads elements as the user scrolls down the list.
- You may show your list using react-virtualized-auto-sizer to make it fit the available space in its parent container.
Let’s take a look at the code. Similar to all other examples, we will make a list using the faker library and will be simulating the loading using setTimeOut of 300 ms inside the loadMoreItems function.
Overscanning
A virtualized list's elements only update as the user scrolls, thus a quick flash of blank space might signal the impending appearance of fresher entries. To see this, rapidly browse through any of the preceding examples in this guide.
To improve the UX of virtualized or windowed lists, react-window allows you to overscan items with the overscanCount property. This allows you to define how many items outside of the visible "window" to render at all times.
Both the FixedSizeList and VariableSizeList components can use overscanCount, which by default has a value of 1. Overscanning more than one entry can assist prevent a perceptible flash of empty space when the user scrolls, depending on how big a list is and how big each item is. Overscanning, on the other hand, can harm performance if done with too many entries. Try to keep the number of overscanned items as low as you can because the whole goal of utilizing a virtualized list is to reduce the number of entries to what the user can view at any given time.
Use the overscanColumnsCount and overscanRowsCount attributes for FixedSizeGrid and VariableSizeGrid to specify the number of columns and rows to overscan, accordingly.
Example for Understanding
We have already been through multiple examples while understanding the various ways of using the React Window library and its wrappers. Here is a sweet little example of the same which illustrates a beautiful feature of this React Window library.
You might have come across some websites where on scrolling you get to see some animation or some indication of scrolling and when the scrolling stops the new data gets loaded. We will be coding the same thing here! Let’s get started!
Let us now see the interesting output!
Explanation
There you go! As long as the scrolling takes place we get the message “Scrolling! Stop to see new Data!”. As soon as it stops the data gets loaded. Now, that is something you can integrate into your website!
Turbocharge Your React Journey! Dive into Our Full Stack Training Course with React-Expert Instructors. Enroll Now!
Conclusion
In this article, we have been through some very useful libraries while developing your project! Let’s take a look at a quick summary of the article:
- Displaying huge lists all at once can lead to slow websites and jerky scrolling effects.
- Virtualization or Windowing is a concept of displaying just enough data to fill the viewport of the user. As the user scrolls, new data are loaded. This optimizes the website as the entire huge list of data is not required to be rendered at the same time.
- React Window or react-window is a third-party library that enables us to implement the concept of virtualization or windowing seamlessly.
- We can apply virtualization or windowing using React Window in many ways depending on the list to be displayed:
- Fixed-sized list
- Variable-sized lists
- Grids
- Lazy loading
- Overscanning
- One of the most common use cases of virtualization or windowing is as an alternative for pagination. In pagination we need to click a button to get the next content, using react window we can make the experience seamless as the next data gets loaded just by scrolling. We can also add some animation while the new data gets loaded to make things look better.