Infinite scroll with pagination, React.js and Typescript

Rasmus Eriksson
2 min readJun 5, 2019

--

You have an API endpoint that returns a pageable result and you are tasked with implementing an infinite scroll. In this write up, I’ll show you how to implement it with React and Typescript.

The basic scenario is the following, we have a search of some sort and when scrolling down we are going to fetch content dynamically to save bandwidth and rendering time (see the image below).

This tutorial will not explain how the wiring to the APIs, redux and so on. We are focusing on building components that can be reused in whatever frameworks is used to shuffle and store data.

The first idea that strucks the mind is to implement some kind of “event” that is triggered when the user is scrolling down and reaching some threshold.

So we scroll down and we trigger a function that calls some function for more data? Solved, that was easy!

Well, yes if you add some restrictions like:

  • There will always be enough data so the view is actually scrollable
  • The number of elements that is added in the fetch causes the scroll height to increase enough for the user to actually have to scroll down more to fetch new content and so on

Just adding the trigger function can create some weird bugs and artifacts where the user has to scroll up and then down again to trigger the function if not enough data is loaded into the view. These bugs can also show themselves when we have a very large screen and the data we fetch is not enough to make the view scrollable or when the API is limited to only return a very small subset of the data. We could add a function, if the page is not scrollable fill with more elements until there are no more.

So we are going with a hybrid approach. Basically, we will poll the div container/wrapper and fetch data if the following is assumed:

  • We are at the bottom OR We have not overflown the div AND we have more results to fetch

To accomplish this we need a stateful component in React.js.

We assume the API resource will return the following with the request:

  • index, the current page we want to get
  • next, a pointer to the next page (if any)
Handles backoff when we poll too aggressively
Helper class for custom styling of components

We use a dynamic intervaller based on setTimeout with some custom logic to make sure it will not produce memory leaks.

This is an example of how the wiring can look like for a connected component.

--

--