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
npm install react-use-infinite-scroll
or
yarn add react-use-infinite-scroll
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.
import React, { useEffect} from 'react';import { useInfiniteScroll } from 'react-use-infinite-scroll';import { useSocialItemsContext } from './context/social-items';import { SocialEntity } from './shared/models';import { BaseLayout, Card } from './components';
const App: React.FC = (): JSX.Element => { const { state: { items, currentPage }, setCurrentPage, } = useSocialItemsContext();
const loadMore = () => setCurrentPage(currentPage + 1); useInfiniteScroll(loadMore); return ( <BaseLayout> {items.map((item: SocialEntity): JSX.Element => ( <Card item={item} key={item.title} /> ))} </BaseLayout>
);};export default App;
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!