Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Pagination with useQuery | Advanced Query Patterns
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
TanStack Query Server State Management in React

bookPagination with useQuery

Handling paginated data is a common requirement when working with APIs that return large datasets. Pagination splits results into discrete pages, each containing a subset of the total data. This approach improves performance, reduces bandwidth, and provides a smoother user experience. There are two primary pagination strategies: page-based and cursor-based. In page-based pagination, you request a specific page number and page size, while cursor-based pagination uses a pointer (cursor) to fetch the next set of results. TanStack Query makes it straightforward to fetch and cache paginated data, especially with page-based pagination, by leveraging query keys and React state.

To implement page-based pagination with useQuery, you maintain the current page in your component's state and include it as part of the query key. This ensures that each page's data is cached separately. For example, suppose you have an API endpoint /api/items?page=1. You can fetch and display paginated data as follows:

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";

function fetchItems(page) {
  return fetch(`/api/items?page=${page}`).then((res) => res.json());
}

function PaginatedItems() {
  const [page, setPage] = useState(1);

  const { data, isLoading, isError } = useQuery({
    queryKey: ["items", page],
    queryFn: () => fetchItems(page),
    keepPreviousData: true,
  });

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error fetching data.</div>;

  return (
    <div>
      <ul>
        {data.items.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>

      <button
        onClick={() => setPage((old) => Math.max(old - 1, 1))}
        disabled={page === 1}
      >
        Previous
      </button>

      <span> Page {page} </span>

      <button
        onClick={() => setPage((old) => old + 1)}
        disabled={!data.hasMore}
      >
        Next
      </button>
    </div>
  );
}

In this example, the query key ["items", page] uniquely identifies each page of data. The keepPreviousData: true option helps maintain the previous page's data in the UI while loading the next page, resulting in a smoother user experience.

When working with paginated queries, managing page state and caching are crucial for performance and usability. The page number is typically stored in React state, allowing the user to navigate between pages. By including the page number in the query key, TanStack Query automatically caches each page's data separately. This means that if a user navigates back to a previously viewed page, the data can be retrieved instantly from the cache without making another network request.

Additionally, using options like keepPreviousData allows you to avoid UI flickers when moving between pages. TanStack Query will keep showing the previous page's data while fetching the new page, then seamlessly update the UI when the new data arrives. This approach balances fast navigation with up-to-date data, and also leverages TanStack Query's caching for efficient resource usage.

question mark

Which statement best describes how query keys are used to cache paginated data in TanStack Query, based on the page-based pagination example above?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 4. Kapitel 2

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Suggested prompts:

Can you explain the difference between page-based and cursor-based pagination?

How does the `keepPreviousData` option improve the user experience?

Can you walk me through how caching works with TanStack Query in this example?

bookPagination with useQuery

Swipe um das Menü anzuzeigen

Handling paginated data is a common requirement when working with APIs that return large datasets. Pagination splits results into discrete pages, each containing a subset of the total data. This approach improves performance, reduces bandwidth, and provides a smoother user experience. There are two primary pagination strategies: page-based and cursor-based. In page-based pagination, you request a specific page number and page size, while cursor-based pagination uses a pointer (cursor) to fetch the next set of results. TanStack Query makes it straightforward to fetch and cache paginated data, especially with page-based pagination, by leveraging query keys and React state.

To implement page-based pagination with useQuery, you maintain the current page in your component's state and include it as part of the query key. This ensures that each page's data is cached separately. For example, suppose you have an API endpoint /api/items?page=1. You can fetch and display paginated data as follows:

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";

function fetchItems(page) {
  return fetch(`/api/items?page=${page}`).then((res) => res.json());
}

function PaginatedItems() {
  const [page, setPage] = useState(1);

  const { data, isLoading, isError } = useQuery({
    queryKey: ["items", page],
    queryFn: () => fetchItems(page),
    keepPreviousData: true,
  });

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error fetching data.</div>;

  return (
    <div>
      <ul>
        {data.items.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>

      <button
        onClick={() => setPage((old) => Math.max(old - 1, 1))}
        disabled={page === 1}
      >
        Previous
      </button>

      <span> Page {page} </span>

      <button
        onClick={() => setPage((old) => old + 1)}
        disabled={!data.hasMore}
      >
        Next
      </button>
    </div>
  );
}

In this example, the query key ["items", page] uniquely identifies each page of data. The keepPreviousData: true option helps maintain the previous page's data in the UI while loading the next page, resulting in a smoother user experience.

When working with paginated queries, managing page state and caching are crucial for performance and usability. The page number is typically stored in React state, allowing the user to navigate between pages. By including the page number in the query key, TanStack Query automatically caches each page's data separately. This means that if a user navigates back to a previously viewed page, the data can be retrieved instantly from the cache without making another network request.

Additionally, using options like keepPreviousData allows you to avoid UI flickers when moving between pages. TanStack Query will keep showing the previous page's data while fetching the new page, then seamlessly update the UI when the new data arrives. This approach balances fast navigation with up-to-date data, and also leverages TanStack Query's caching for efficient resource usage.

question mark

Which statement best describes how query keys are used to cache paginated data in TanStack Query, based on the page-based pagination example above?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 4. Kapitel 2
some-alt