React Infinite Scroll Hook, and Handling Window Events With Hooks

Infinite scroll is one of those really nice to have and really hard to make features, here I will show you hao you can do just that in two lines of code with a little helper library called react-use-infinite-scroll.

So assume that we already have a React project set up, let’s install this library


If we say that we have some home page that needs to load more entities, we will usually track the position of the scrollbar on the screen, we will have to worry about subscribing/unsubscribing on window events and so on, what I find really useful about this library is that is abstracting all of that from us and just exposes simple API where we just register a callback that we want to fire when end of the screen is reached.

So, for example, let us say that we have some sort of home page where we need to show some cards with social entity data, and to have load more feature as the user reaches the end of the screen.

So let’s take another look, as you can see I’ve defined this function loadMore that is changing the current page in the context, and that triggers an API call for more data, but I don’t want to bother you with that, let’s focus on how and when are we loading new data.

When we say useInfiniteScroll(loadMore); we have now registered the load more callback every time the user reaches the end of the screen, which is the behavior we want, and once our component unmounts this hook will do the cleaning after itself and unregister event listeners for you.

So yeah, that is that, pretty simple, right? Happy codding!

Highly motivated, dedicated developer. I’m also a functional programming enthusiast and that is something that I’m exploring in the last couple of years.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store