The Storefront API limits how many items can be queried at once. This encourages better app performance by only querying what's immediately necessary to render the page.
However, sometimes you might have long lists of products, collections, or orders. Rather than rendering every item in the list, for better performance you should only render one page at a time. The Storefront API uses cursors to paginate through lists of data and the
Pagination component enables you to render those pages.
It's important to maintain the pagination state in the URL for the following reasons:
- Users can navigate to a product and return back to the same scrolled position in a list.
- The list state is shareable by URL.
- Search engine crawlers are also able to index the pages when the pagination state is stored in the URL,
To set up pagination inside your app, do the following tasks:
Setup the paginated queryAnchor link to section titled "Setup the paginated query"
First, set up a GraphQL query to the Storefront API to return paginated content. A query needs to have the arguments
The query response needs to include
endCursor passed to it.
Hydrogen provides the utility
getPaginationVariables to help calculate these variables from URL parameters. We recommend using the utility to pass the variables to the query within your loader:
Render the Anchor link to section titled "Render the Pagination component"
Pass the entire query connection to the
Pagination component. The component provides a
render prop with all the nodes in the list. Map the nodes by product ID and render them.
Pagination component's render prop provides convenience links to either load more or previous product pages from nodes:
Complete pagination exampleAnchor link to section titled "Complete pagination example"
The following is a complete example of data fetching using pagination:
Automatically load pages on scrollAnchor link to section titled "Automatically load pages on scroll"
We can change the implementation to support loading subsequent pages on scroll. Add the dependency
react-intersection-observer and use the following example: