---
title: Pagination
description: >-
  Paginate a Firestore query using orderBy(), limit() and startAfter() query
  constraints.
next: /firestore/pipelines
previous: /firestore/usage-with-flatlists
---
> ## Documentation Index
> Fetch the complete documentation index at: https://rnfirebase.io/llms.txt
> Use this file to discover all available pages before exploring further.

## Prerequisites

- `@react-native-firebase/app` installed and native config completed per [Getting Started](/) (Android `google-services.json`, iOS `GoogleService-Info.plist`, Expo config plugin, or React Native CLI setup). From v26, New Architecture is required for packages with a native bridge.
- `@react-native-firebase/firestore` installed: `npm install --save @react-native-firebase/firestore` or `yarn add @react-native-firebase/firestore`, then rebuild native apps (`cd ios && pod install` on iOS).
- A Cloud Firestore collection named `Users` with documents that include `name` and `age` fields (adjust the field names and page size below to match your schema).

Pagination using Cloud Firestore may be done in various ways. This page shows a basic approach using the Firestore query features
`orderBy`, `limit`, and `startAfter`.

# Setup state

First, create a list display component with 2 state items; `lastDocument` and `userData`:

```jsx
import React, { useState } from 'react';
import { View, Button } from 'react-native';
import { collection, getFirestore } from '@react-native-firebase/firestore';

const db = getFirestore();
const usersRef = collection(db, 'Users');

function App() {
  const [lastDocument, setLastDocument] = useState(undefined);
  const [userData, setUserData] = useState([]);

  return (
    <View>
      {userData}
      <Button
        onPress={() => {
          console.log('Wire LoadData in the next example. usersRef:', usersRef.path);
          console.log('lastDocument:', lastDocument);
          setLastDocument(lastDocument);
          setUserData(userData);
        }}
        title="Load Next"
      />
    </View>
  );
}

export default App;
```

# `LoadData` function

Next, make a function called `LoadData` that fetches data from the `Users` collection, and call it when a `Button` is pressed.

If `lastDocument` is not assigned (meaning initial load), the function will fetch from the start.
After a successful fetch from the collection, store the last snapshot via `setLastDocument`.

`startAfter(lastDocument)` takes a `DocumentSnapshot` as the cursor. The snapshot must exist and must contain the field used in `orderBy` (`age` here), and documents without that field never appear in the query. React Native Firebase also sorts by document id after the `orderBy` field for snapshot cursors, so users with the same `age` are not skipped or repeated between pages. An empty page means there is nothing left, so the sample keeps the previous cursor instead of resetting it. See [Start/End](/firestore/usage#startend) for the other cursor constraints (`startAt`, `endAt`, and `endBefore`).

```jsx
import React, { useState } from 'react';
import { Text, View, Button } from 'react-native';
import {
  collection,
  getDocs,
  getFirestore,
  limit,
  orderBy,
  query,
  startAfter,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const usersRef = collection(db, 'Users');

function App() {
  const [lastDocument, setLastDocument] = useState(undefined);
  const [userData, setUserData] = useState([]);

  function MakeUserData(docs) {
    const templist = [];
    docs.forEach(docSnapshot => {
      const data = docSnapshot.data();
      console.log(data);
      templist.push(
        <View key={docSnapshot.id} style={{ margin: 10 }}>
          <Text>{data.name}</Text>
          <Text>{data.age}</Text>
        </View>,
      );
    });
    setUserData(templist);
  }

  function LoadData() {
    console.log('LOAD');
    const pageQuery =
      lastDocument !== undefined
        ? query(usersRef, orderBy('age'), startAfter(lastDocument), limit(3))
        : query(usersRef, orderBy('age'), limit(3));

    getDocs(pageQuery)
      .then(querySnapshot => {
        if (querySnapshot.empty) {
          // Keep the previous cursor: clearing it would restart pagination from the first page.
          console.log('No more pages');
          return;
        }
        setLastDocument(querySnapshot.docs[querySnapshot.docs.length - 1]);
        MakeUserData(querySnapshot.docs);
      })
      .catch(error => {
        console.error('Loading page failed:', error.code, error.message);
      });
  }

  return (
    <View>
      {userData}
      <Button
        onPress={() => {
          LoadData();
        }}
        title="Load Next"
      />
    </View>
  );
}

export default App;
```

# `MakeUserData` function

`MakeUserData` is an example helper that turns query documents into React Native views. Alter it to process the data to meet your requirements.
In this specific example, it replaces the `userData` component tree with the page just fetched. To append pages instead of replacing them, start from `[...userData]` rather than `[]`.

# Conclusion

Here is the full example code:

```jsx
import React, { useState } from 'react';
import { Text, View, Button } from 'react-native';
import {
  collection,
  getDocs,
  getFirestore,
  limit,
  orderBy,
  query,
  startAfter,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const usersRef = collection(db, 'Users');

function App() {
  const [lastDocument, setLastDocument] = useState(undefined);
  const [userData, setUserData] = useState([]);

  function LoadData() {
    console.log('LOAD');
    const pageQuery =
      lastDocument !== undefined
        ? query(usersRef, orderBy('age'), startAfter(lastDocument), limit(3))
        : query(usersRef, orderBy('age'), limit(3));

    getDocs(pageQuery)
      .then(querySnapshot => {
        if (querySnapshot.empty) {
          // Keep the previous cursor: clearing it would restart pagination from the first page.
          console.log('No more pages');
          return;
        }
        setLastDocument(querySnapshot.docs[querySnapshot.docs.length - 1]);
        MakeUserData(querySnapshot.docs);
      })
      .catch(error => {
        console.error('Loading page failed:', error.code, error.message);
      });
  }

  function MakeUserData(docs) {
    const templist = [];
    docs.forEach(docSnapshot => {
      const data = docSnapshot.data();
      console.log(data);
      templist.push(
        <View key={docSnapshot.id} style={{ margin: 10 }}>
          <Text>{data.name}</Text>
          <Text>{data.age}</Text>
        </View>,
      );
    });
    setUserData(templist);
  }

  return (
    <View>
      {userData}
      <Button
        onPress={() => {
          LoadData();
        }}
        title="Load Next"
      />
    </View>
  );
}

export default App;
```

Every time the button is pressed, `Users` collection data is fetched one page at a time.
