useCollection
Hook
useCollection
hook is used to list a collection in Firebase. A very simple example would be:
const colRef = collection(firestore, "collectionName");
const { loading, snapshot, error } = useCollection(colRef);
You can also pass in a customized query:
const colRef = collection(firestore, "collectionName");
const query = query(colRef, where("field", "==", "value"));
const { loading, snapshot, error } = useCollection(query);
By default, useCollection
lists a collection only once. If you need realtime updates, you can set options.listen
to true
as below:
const { loading, snapshot, error } = useCollection(colRef, { listen: true });
Input Parameters
Input parameters for useCollection
hook is as follows:
Name | Type | Description | Required | Default Value |
---|---|---|---|---|
reference |
firebase/firestore/CollectionRefference or firebase/firestore/Query |
Reference to a collection in Firestore or a query. | ✅ | - |
options |
Object | Options for the hook. | ❌ | See below. |
options.listen |
boolean |
Whether to listen to realtime changes of the document or not. | ❌ | false |
options.listenToMetadataChanges |
boolean |
Whether to listen to realtime changes of the document or not as well as its metadata. See this. | ❌ | false |
Note
options.listen
is false
by default to prevent unnecessary READ queries from Firestore.
Return Type
useCollection
hook returns an object with properties as below:
Name | Type | Description |
---|---|---|
loading |
boolean |
Whether the hook is loading the collection or not. |
snapshot |
firebase/firestore/QuerySnapshot or undefined |
Snapshot of the retrieved document. |
error |
firebase/FirebaseError or undefined |
The instance of error if any. |
Warning
Only firebase/FirebaseError
is caught if any. error
will not be an instance of another type.