Infinite scrolling is a feature that allows you to load content continuously when users scroll down the page. It is widely used in social media apps such as Facebook, Twitter, Instagram, etc. I happened to implement this feature with react recently and I would like to share my experience and thoughts on this topic.

## How to implement

Let me cut to the chase, what I did is to use this react-infinite-scroller npm package. It is actually quite easy to use. You just need to wrap your content with the InfiniteScroll component and pass the loadMore function as a prop. The loadMore function will be called when the user scrolls down to the bottom of the page.

<InfiniteScroll
        pageStart={0}
        loadMore={loadFunc}
        hasMore={true || false}
        loader={<div className="loader" key={0}>Loading ...</div>}
        useWindow={false}
    >
        {items}
    </InfiniteScroll>

what you need to prepare is 1. The loadFunc which will retrieve the next batch of data and 2. The hasMore flag which indicates whether there is more data to load. Becides, you can customize the style of the loader and the parent container.

One thing the document assumes is that you already know how to do state management. The case is that you need to store the data you have loaded and append the new data to the existing data. The simplest way to do this is to use useState hook.

const [data, setData] = useState([])
const [page, setPage] = useState(0)
const loadFunc = () => {
    // fetch data from backend
    // append the new data to the existing data
    newdata = fetch(page)
    setData(append(data, newData))
}

in the above code, we use page to indicate the current page of data. When the user scrolls down to the bottom of the page, we fetch the next page of data and append it to the existing data. It should sufice for most cases.

How it works

Actually before I found this package, I was looking at some tutorials on how to implement infinite scrolling from scratch. I basically searched on youtube and found this two https://www.youtube.com/watch?v=NZKUirTtxcg and https://www.youtube.com/watch?v=JWlOcDus_rs Both are well explained but the first one is a bit outdated. So if you follow the second one and check the repository, you will roughly get how this works.

so the key is to detect when the user scrolls down to the bottom of the page. The way to do this is to set up a useRef hook and attach a callback function to the intersection observer.


   const intObserver = useRef()
    const lastPostRef = useCallback(post => {
        if (isLoading) return

        if (intObserver.current) intObserver.current.disconnect()

        intObserver.current = new IntersectionObserver(posts => {
            if (posts[0].isIntersecting && hasNextPage) {
                console.log('We are near the last post!')
                setPageNum(prev => prev + 1)
            }
        })

        if (post) intObserver.current.observe(post)
    }, [isLoading, hasNextPage])

The above code is from the second tutorial. The intObserver is the intersection observer we set up. The lastPostRef is the ref of the last post. When the user scrolls down to the last post, the callback function will be called. In the callback function, we check if the user is scrolling down and there is more data to load. If so, we call the setPageNum function to load the next page of data.

Let’s take a look at the npm package I used. Its source code is actully neat with one file https://github.com/danbovey/react-infinite-scroller/blob/master/src/InfiniteScroll.js it is using low level api to detect the scroll events which make it approriate as a universal package that supports you simply config and set up the related functions.