isPreviousData checks what data the query is currently providing.As soon as the new data arrives, the previous data will be swapped with the new data.The previous data from the last successful fetch will be available even though the query key has changed.Setting the keepPreviousData to true will give us the following benefits: To implement pagination, we ideally need to increment or decrement the pageIndex, or cursor, for a query. A query is a declarative dependency on an asynchronous source of data that has a unique key. The useQuery Hook is used to fetch data from an API. Pagination with useQuery and keepPreviousData Then, we wrap the app with Quer圜lientProvider as shown below: //App.js To initialize a new instance of React Query, we’ll import Quer圜lient and Quer圜lientProvider from React Query. Start the server with npm start, and let’s dive in! Setting up React Query We’ll start by initializing a new React app and installing React Query as follows: npx create-react-app app-name React Query offers features like data caching, deduplicating multiple requests for the same data into a single request, updating state data in the background, performance optimizations like pagination and lazy loading data, memoizing query results, prefetching the data, mutations, and more, which allow for seamless management of server-side state.Īll of these functionalities are implemented with just a few lines of code, and React Query handles the rest in the background for you.
React Query makes it easy to fetch, cache, sync, and update server state in React applications.
This article assumes that you have a basic understanding of React. We’ll use the Random User API, which allows you to fetch up to 5,000 random users either in one request or in small chunks with pagination. In this tutorial, we’ll learn how to implement pagination and infinite scroll using React Query. These patterns improve an application’s performance by only rendering or fetching small chunks of data at a time, greatly improving UX by allowing users to easily navigate through the data. Two popular UI patterns that frontend developers can use to efficiently render large data sets are pagination and infinite scroll. When large data sets are handled incorrectly, both developers and end users feel the negative effects. Pagination and infinite scroll with React Query v3 Chiamaka Umeh Follow A frontend developer with a passion for designing highly-responsive user interfaces for JavaScript-based web and mobile apps using React and React Native.