Infinite scroll in React made easy with Intersection Observer
When we want to do infinite scroll list what will get strike in our mind is that let’s listen for scroll event, when the scroll reach down the bottom of the list container, call API to get further list item.
While implementing this approach we should show some extra care when calculating whether the scroll reach down the bottom because scroll event will fire continuously.
To rescue us from the above overhead, a new API has arrived in majority of the browser called IntersectionObserver.
What IntersectionObserver API does is that, it notifies us whenever observed DOM element is intersect(enter / hide) with it’s parent element / viewport. I would recommend you to just go through this new API one here to understand it’s usage well.
Let’s see how we can use this API to implement infinite scroll list, approach is so simple, In older ways (eg:- litening for scroll event ) we will conditionally show the loading-image when the scroll bar has reached the bottom position to inform the user that some more data is loading into the list when ajax request is being processed.
In our new approach, instead of conditionally showing the loading-image when making ajax request once scrollbar reached bottom position, we will always show the loading-image at the bottom of the list by considering loading-image is also a part of list item.
And then we will observe the loading-image using Intersection Observer whether loading-image is being visible in the UI or not. If it is visible in the UI (that means scroll bar is at the bottom), then we can make ajax request to get some new data. Once a new data is pushed into the list, loading-image will automatically get pushed to bottom ( which means that loading-image is pushed out of viewport).
Using this approach i have written a react component which will notify whenever loading bar is visible in UI, so that you can do your wish.
And also I have written an another React HigherOrderComponent, which will remove it’s children from DOM whenever it is not visible to user, This will help to make smooth infinite scroll. Because you can have 1000 items in the array, but only few numbers of item a user can see in the screen based on the screen size. So it is good practice to hide the DOM from view that are non visible to user and add them back into the view when the user scroll into it.
This component will help to do this.
Following is the full example of doing infinite scroll list using above two components without listening for scroll event.