Chakra UI Pagination + React Query: Controlled or Uncontrolled State?
0 reputation · 10 Nov 2021, 14:56 UTC
0 reputation · 10 Nov 2021, 14:56 UTC
Goal: Ensure that Chakra UI's Pagination component stays in sync with a data‑fetching hook such as React Query when implementing paginated loading of large datasets.
The Pagination component is stateless and requires a pageIndex prop and an onChange handler, forcing a controlled pattern. React Query, meanwhile, owns the query state and can refetch when pagination parameters change. This creates a boundary where the source of truth for the current page can live either in the Pagination UI or in the query hook, leading to uncertainty about which approach avoids prop mismatches, unnecessary re‑renders, or UI jumps when the dataset size changes.
Should the Pagination be left uncontrolled so it manages its own index internally? If kept controlled, how should the pageIndex be derived from React Query's state to prevent stale props? What safeguards prevent desynchronization when the total record count or filter criteria update?
33775 reputation · 11 Nov 2021, 02:18 UTC
The Chakra UI Pagination component is stateless and requires page (or pageIndex) and onPageChange. To stay in sync with React Query, the single source of truth for the current page should live in your own state (or URL) and be passed into both the query key and the Pagination props.
queryKey changes.page is supplied; it only calls onPageChange with the new value.const [page, setPage] = useState(1);queryKey: ['items', { page, pageSize, filters }]<Pagination.Root
count={total}
pageSize={pageSize}
page={page}
onPageChange={(e) => setPage(e.page)}>
{/* pagination items */}
</Pagination.Root>keepPreviousData: true (v4) or placeholderData: keepPreviousData (v5).const maxPage = Math.max(1, Math.ceil(total / pageSize)); const clamped = Math.min(page, maxPage); and use clamped as the value passed to Pagination.To verify that the API matches the example, confirm which version of @chakra-ui/react you have installed. Chakra UI v2 does not export a Pagination component; v3 introduces the controlled/uncontrolled API shown above.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.