Blog>
Snippets

Handling Pagination with React Query

Showcase handling pagination with React Query by using the keepPreviousData option in the useQuery hook to prevent UI flickers while fetching new pages.
import { useQuery } from 'react-query';

// Function to fetch users
const fetchUsers = async (page = 1, limit = 10) => {
  const response = await fetch(`http://localhost:3004/users?_page=${page}&_limit=${limit}`);
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
Defines the fetchUsers function, which makes an HTTP GET request to the backend. It is designed to fetch a specific page of users, taking page and limit as arguments.
function PaginatedComponent() {
  const [page, setPage] = useState(1);
  const {
    data, isLoading, isError, error,
    isFetching, isSuccess
  } = useQuery(['users', page], () => fetchUsers(page), {
    keepPreviousData: true,
    staleTime: 5000,
    cacheTime: 10000
  });

  // Event handlers for pagination
  const nextPage = () => setPage(old => old + 1);
  const prevPage = () => setPage(old => Math.max(old - 1, 1));

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error: {error.message}</div>;

  return (
    <div>
      {data && (
        <div>
          {data.map(user => (
            <p key={user.id}>{user.name}</p>
          ))}
        </div>
      )}
      <button onClick={prevPage} disabled={page === 1}>Previous Page</button>
      <button onClick={nextPage} disabled={isFetching}>Next Page</button>
    </div>
  );
}
This component utilizes the useQuery hook for fetching and displaying users. It includes nextPage and prevPage functions for pagination. The keepPreviousData option is set to true to avoid UI flickers when moving between pages.