Pagination in React Query 2025

Pagination in React Query 2025

React Query ke sath pagination implement karne ke liye aapko backend se paginated data fetch karna hoga, aur use dynamically load karna hota hai next/previous buttons ke through.

Step-by-step Code:


// PaginationComponent.jsx
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import { useState } from "react";

const fetchUsers = async (page) => {
  const { data } = await axios.get(`https://reqres.in/api/users?page=${page}`);
  return data;
};

export default function PaginationComponent() {
  const [page, setPage] = useState(1);

  const { data, isLoading, isError, isFetching } = useQuery({
    queryKey: ['users', page],
    queryFn: () => fetchUsers(page),
    keepPreviousData: true
  });

  if (isLoading) return 

Loading...

; if (isError) return

Something went wrong

; return (
    {data.data.map((user) => (
  • {user.first_name} {user.last_name}
  • ))}
Page: {page}
{isFetching ?

Fetching...

: null}
); }

Key Points:

  • keepPreviousData: Yeh ensure karta hai ki jab aap next page per jayein toh pichla data remove na ho jaye turant.
  • queryKey: ['users', page] – har page ke liye unique queryKey hota hai.
  • Buttons: "Previous" aur "Next" ke through page update hota hai.

Use Case:

Jab aapko large datasets dikhani ho, jaise users list, orders ya posts, toh pagination aapki performance aur UX dono ko enhance karta hai.