---
title: Usage with FlatLists
description: >-
  Render a Firestore collection in a React Native FlatList: subscribe with
  onSnapshot(collection(db, ...)), map QuerySnapshot documents into a keyed
  array, and update the list in realtime.
next: /firestore/pagination
previous: /firestore/emulator
---
> ## 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 at least a `name` field (adjust the field names below to match your schema).

Cloud Firestore provides out of the box support for subscribing to [realtime changes](/firestore/usage#realtime-changes)
on a collection of documents. Whilst building apps with Cloud Firestore, you can easily display lists of a collections
documents using a [`FlatList`](https://reactnative.dev/docs/flatlist.html).

A `FlatList` accepts an array of data, and displays the results in a performance friendly scrollable list. By integrating
a realtime listener with the `FlatList`, whenever data changes in your database it will automatically and efficiently update
on your application.

# Setup state

First, set up a component which will display the list of data. The component has 2 separate states; `loading` and
`users`:

```jsx
// codeblock-ignore: setLoading and setUsers are wired up in the next step
import React, { useState } from 'react';
import { ActivityIndicator, View } from 'react-native';

function Users() {
  const [loading, setLoading] = useState(true); // Set loading to true on component mount
  const [users, setUsers] = useState([]); // Initial empty array of users

  if (loading) {
    return <ActivityIndicator />;
  }

  return <View>{/* FlatList is wired up in the complete example below */}</View>;
}

export default Users;
```

# `useEffect` hook

Next, set up a hook with `useEffect`. This hook triggers when the component mounts, and then subscribes to
the `Users` collection documents:

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

const db = getFirestore();

function Users() {
  const [loading, setLoading] = useState(true); // Set loading to true on component mount
  const [users, setUsers] = useState([]); // Initial empty array of users

  useEffect(() => {
    const subscriber = onSnapshot(
      collection(db, 'Users'),
      querySnapshot => {
        const nextUsers = [];

        querySnapshot.forEach(documentSnapshot => {
          nextUsers.push({
            ...documentSnapshot.data(),
            key: documentSnapshot.id,
          });
        });

        setUsers(nextUsers);
        setLoading(false);
      },
      error => {
        console.error('Users listener failed:', error.message);
        setLoading(false);
      },
    );

    // Unsubscribe from events when no longer in use
    return () => subscriber();
  }, []);

  if (loading) {
    return <ActivityIndicator />;
  }

  // The complete example below renders `users` in a FlatList
  return (
    <View>
      <Text>{users.length} users</Text>
    </View>
  );
}

export default Users;
```

The second callback receives listener errors such as `firestore/permission-denied`. Without it, a rejected listener never calls the first callback and the screen stays on the loading indicator, and a listener registered with a single function receives `null` instead of a snapshot when it fails (see [Realtime changes](/firestore/usage#realtime-changes)).

# Transforming data

Whilst iterating the collection documents, create an array of data a `FlatList` accepts. At a minimum, this is an object with a unique `key` property (`FlatList` reads `item.key` by default; pass `keyExtractor` to use another field). For this unique property,
use the `id` of a document. The `useEffect` example above already maps each document with `key: documentSnapshot.id`.

Once the initial set of documents is returned, update the `users` state with the raw object data and set the `loading`
state to `false`.

# Integration

With the raw user data in local state, pass it to the `FlatList`:

```jsx
import React, { useState, useEffect } from 'react';
import { ActivityIndicator, FlatList, View, Text } from 'react-native';
import { collection, getFirestore, onSnapshot } from '@react-native-firebase/firestore';

const db = getFirestore();

function Users() {
  const [loading, setLoading] = useState(true);
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const subscriber = onSnapshot(
      collection(db, 'Users'),
      querySnapshot => {
        const nextUsers = [];

        querySnapshot.forEach(documentSnapshot => {
          nextUsers.push({
            ...documentSnapshot.data(),
            key: documentSnapshot.id,
          });
        });

        setUsers(nextUsers);
        setLoading(false);
      },
      error => {
        console.error('Users listener failed:', error.message);
        setLoading(false);
      },
    );

    return () => subscriber();
  }, []);

  if (loading) {
    return <ActivityIndicator />;
  }

  return (
    <FlatList
      data={users}
      renderItem={({ item }) => (
        <View style={{ height: 50, flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Text>User ID: {item.key}</Text>
          <Text>User Name: {item.name}</Text>
        </View>
      )}
    />
  );
}

export default Users;
```

With little effort, the list will automatically update in realtime whenever a document is added, removed, or modified.
This functionality can be further manipulated to respond to user filters via [Querying](/firestore/usage#querying) if required.
