The useCollection
hook makes it simple to connect with realtime Firestore collections, even when paths are dynamic or depend on the ID of the current user. This hook is particularly useful in React applications where collection paths depend on runtime values like user IDs or route parameters.
useCollection
is to provide a CollectionReference
or QueryReference
to the hook. This will fetch the documents and return their data. The hook will also automatically update the component with the latest data whenever a document changes.
First, let’s connect to all of the books in our Firestore database:
CollectionReference
or QueryReference
directly, we’ll need to provide a function which can produce one. This function’s first argument will be the user ID of the active user.
useEffect
hook.
For example, we might want to display a set of Book
documents that share the same authorId
as a the book we’re currently displaying. In this case, the query we want to connect to depends on the book document.