How to render a large list effectively in React?
Let’s virtualize a list with react-window
You might often display large data as a front-end developer. If You fetch large amounts of data and just display them at once, It is likely to be slow or frozen sometimes. Displaying a large list is expensive. So How can we render this big data effectively? There are several ways. The most simplest but powerful way is to use pagination. Pagination can be implemented in various ways like using the button, infinite scroll, and more.
Today, I will introduce react-window library by bvaughn. React-window provides components that are purposed to render part of the dataset which is visible to the user’s viewport. This technique is called “windowing” or “List virtualization”. react-window is the same as react-virtualized by bvaughn but it is lighter-weight than react-virtualized.
If you want to know more information, You can check Virtualize Long List, in React’s official documentation.
What is Windowing or List virtualization?
“Windowing” is a technique to move the window in a virtualized list. The window is a viewport that the user currently sees. Only rendering the amount of data in the window can increase performance by reducing the browser’s rendering costs like creating countless DOM nodes, memory usage, styling CSS, layout calculation, and so on.
Let’s see the above image. The user can see only two rows of data. So we can only render two rows of data. If the user scrolls down, render the next two rows of data that are currently in the window.
You can think of Twitter. There are countless feeds and new feed is created constantly in real time. If we render them all at once, it is very painful for an application, as a result, it can make an application malfunction eventually.
Let’s render data with react-window
Ok, It is time to apply react-window. React-window will rescue us!
You can find more information in react-window documentation.
VariableSizeList
I created an example using VariableSizeList
which is a component to render rows having arbitrary heights. Table is great for displaying list data. So I used react-table library with react-window. Paragraph has arbitrary characters so its row height might be dynamic.
If you use variableSizeList or FixedSizeList, you have to set fixed width and height. What if you want to set its height to 100% to stretch all remaining space automatically? AutoSizer
can help you! AutoSizer is a high-order component that automatically adjusts the width and height of a single child.
Infinite Loader
If you want to use react-window and infinite scroll together, use react-window-infinite-loader library.
Conclusion
Rendering large list is expensive. In this case, you can use windowing technique using React-window. It helps your UI faster and smoother.
Happy Coding.