Create an Instagram-like infinite scrolling feed in ReactJS using React Query and React Infinite Scroller

Instagram infinite scrolling feed React Query React Query Infinite Scroller React Infinite Scroller

Infinite scrolling is a popular interaction pattern that allows users to continuously load content while scrolling down a page. This means an app fetches a small chunk of data and continues fetching more data as the user scrolls through.

One of the most common use-cases for this pattern is seen in large-scale social media websites such as Instagram and Twitter. This provides major performance improvements when compared to fetching a website’s entire data during an initial load.

In this article, we’ll learn how to build an Instagram-like infinite scrolling feed in a React application with React Query’s useInifiniteQuery() Hook.

Why use React Query?

React is an unopinionated JavaScript library that builds interactive and scalable web applications. However, this unopinionated nature can also act as a double-edged sword because it does not ship with a built-in data fetching solution.

Although you can implement your own data fetching mechanisms, React Query provides an easier and more efficient way to manage asynchronous server state in the form of Hooks.

These Hooks also come with the added benefits of caching response data, deduping multiple requests, and more performance optimizations.

Some of the most commonly used Hooks from this library are the useQuery() Hook, which fetches data from an API, and the useMutation() Hook, which creates, updates, and deletes server data.

The useInfiniteQuery() The hook is just a modified variant of the useQuery() Hook and provides infinite scrolling functionality.

Understanding the useInfiniteQuery() Hook

Before diving into the project, let’s take a moment to understand how the useInfiniteQuery() Hook works and how to use it. This Hook takes two mandatory parameters: the query key and the query function, along with an optional options object.

This Hook returns values and functions that can retrieve fetched data, check the state of a query (such as errorloadingfetching, or idle), and check whether more pages are present or other information to send to the infinite scroller component.

Creating the Instagram-like infinite scrolling project 

create a new React app on your local machine using the create-react-app tool by running this command:

npx create-react-app react-infinite-scroll

In case you choose to create the React app on your local machine, install React Query and the infinite scroller component using the command given below:

npm install react-query react-infinite-scroller
#or
yarn add react-query react-infinite-scroller

While React Query can help you fetch data, providing the UI implementation of the infinite scroller component is up to you. This is why we’re using the react-infinite-scroller library.

Configuring React Query

Before we can start using the Hooks from React Query, we must import QueryClient and QueryClientProvider from react-query and wrap it around the <App /> component inside the index.js file.

This ensures all the components in the React application have access to the Hooks and cache:

import { QueryClient, QueryClientProvider } from "react-query";
import { ReactQueryDevtools } from 'react-query/devtools'
import ReactDOM from "react-dom";
import App from "./App";
const queryClient = new QueryClient();

ReactDOM.render(
   <QueryClientProvider client={queryClient}>
       <App />
       <ReactQueryDevtools initialIsOpen={false}/>
   </QueryClientProvider>,
   document.getElementById("root")
);

Using the Lorem Picsum API

To display images for the infinite scrolling feed, we’ll use the Lorem Picsum API to fetch an array of images and their information in JSON format. More specifically, we’ll use the following API endpoint:

https://picsum.photos/v2/list?page=1&limit=10

Using the limit query parameter, we can set the number of images fetched per API call to 10. This retrieves 10 images initially and continues fetching 10 more images each time the user is close to reaching the end of the feed.

Creating a narbar component

Create a navbar component using bootstrap CDN CSS link import on the index.html on public folder first 

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

navbar.js

const Navbar = ({ post }) => {
   return (
      <nav className="navbar navbar-expand-md bg-dark navbar-dark">
         <a className="navbar-brand" href="https://www.codesolution.co.in/" target="_blank">Codesolution</a>
      </nav>
   );
};
export default Navbar;

Creating a PostCard component

Let’s make a simple React component to display an image and its author. First, create a folder inside the src directory named components. Inside this components folder, create a new file named PostCard.jsx and paste the following code:

const PostCard = ({ post }) => {
   return (
      <div className="post-card">
         <h4>{post.author}</h4>
         <img src={post.download_url} alt={post.author} />
      </div>
   );
};
export default PostCard;

This component takes a prop named post and uses the author and download_url properties to display the author’s name and image. To style, this component, append the CSS given below to the App.css file:

.main{
    width: 40%;
    margin: auto;
    padding: 10px;
}
.post-card {
    display: flex;
    flex-direction: column;
    border: 1px solid #dbdbdb;
    margin-bottom: 1.5rem;
}
.post-card h4 {
    background: #fafafa;
    padding: 0.5rem;
}
.post-card img { 
    width: '100%';
    object-fit: cover;
}
// remove bottom left logo React Query module
.ReactQueryDevtools{
   display: none;
}

Finally,  Add the following code to App.js:

import InfiniteScroll from "react-infinite-scroller";
import { useInfiniteQuery } from "react-query";
import Navbar from "./components/navbar";
import PostCard from "./components/PostCard";
import "./App.css";
export default function App() {
const fetchPosts = async ({ pageParam = 1 }) => {
   const response = await fetch(
       `https://picsum.photos/v2/list?page=${pageParam}&limit=10`
   );
   const results = await response.json();
       return { results, nextPage: pageParam + 1, totalPages: 100 };
   }; 
   const {
     data,
     isLoading,
     isError,
     hasNextPage,
     fetchNextPage
   } = useInfiniteQuery("posts", fetchPosts, {
       getNextPageParam: (lastPage, pages) => {
       if (lastPage.nextPage < lastPage.totalPages) return lastPage.nextPage;
           return undefined;
        }
  });
return (
   <div className="App"> 
       <Navbar />
       <main className="main">
         {isLoading ? (
             <p>Loading...</p>
         ) : isError ? (
             <p>There was an error</p>
         ) : (
             <InfiniteScroll hasMore={hasNextPage} loadMore={fetchNextPage}>
                {data.pages.map((page) =>
                      page.results.map((post) => <PostCard key={post.id} post={post} />)
                )}
             </InfiniteScroll>
        )}
     </main>
  </div>
 );
}

Conclusion

With this, you’ve successfully built your own infinite scrolling feed of images using React Query, the Lorem Picsum API, and the React InfiniteScroll component. You can use this concept to build any type of infinite scrolling feed for your projects.

About the author
Code solution

info@codesolution.co.in

Discussion
  • 0 comments

Add comment To Login
Add comment