Rendering large lists of data in React efficiently

Rendering large lists of data in React efficiently

·

2 min read

If you're using React and need to efficiently display large lists of data, you can use pagination to display a limited amount of items at a time, or you can use an infinite scrolling component to show all of the data while the user scrolls.

Pagination is useful because it reduces server overhead, improves response time, and avoids unnecessary DOM size by dividing lists up into smaller, discrete "pages".

However, if you're creating a social media app like Twitter that needs to display all of the posts in a feed, rendering all of the data at once can have a major influence on the performance of your app.

In this case, you can improve the performance of your app by using something like the Intersection Observer API which detects if the data being rendered on screen is the last item of your data, and if it is, you fetch more data, similar to how you would fetch data in while pagination, and append the newly fetched data to the data that is already present, giving the user the illusion of infinite scrolling.

Different types of rendering large data list on phone

You can use this react package called react-infinite-scroll-component to build an infinite scrolling component, which is super-simple to integrate or refer to this article if you want to build it on your own.

The above implementation is fine, but if the data contains thousands of items, then it is a problem.

This Google article describes how having an enormous DOM size affects your app's speed, slows down your page performance in various ways, and also affects your lighthouse score.

Virtualization can be utilised to alleviate this problem because users are likely interested in a window with a specific set of rows and will scroll for more information. Maintaining a window and moving it around your list is what "virtualizing" a list entails.

representation of virtualization list on a phone

Rather than rendering 1000s of elements from a list at once (which can cause slower initial rendering or impact scroll performance), virtualization focuses on rendering just items visible to the user.

Libraries like react-window, react-virtuoso etc., can be used to implement virtualization in React.

You can only render fixed height items using react-window; if you wish to render dynamically sized elements, you need to use react-virtuoso.

If you're using React Native to create apps, there's already a built-in virtualization component called ListView or you can use this package called RecyclerListView.

Reference