Skip to content

React - Hooks

Typed hooks for subscribing to Firestore documents and collections in React applications.

useDocument

ts
import { useDocument } from "@typed-firestore/react";

function UserProfile({ userId }: { userId: string }) {
  /** Returns user as FsMutableDocument<User> */
  const [user, isLoading] = useDocument(refs.users, userId);

  if (isLoading) return <Spinner />;

  /** TypeScript knows user.data is available because isLoading is false */
  return <div>{user.data.displayName}</div>;
}

Notice how you don't need to import the User type or manually type your data. Everything flows from the collection refs.

useCollection

ts
import { useCollection } from "@typed-firestore/react";

function BookList() {
  const [books, isLoading] = useCollection(refs.books, (query) =>
    query.where("is_published", "==", true).limit(20),
  );

  if (isLoading) return <Spinner />;

  return books.map((book) => <div key={book.id}>{book.data.title}</div>);
}

API Reference

HookDescription
useDocumentUse a document and subscribe to changes
useDocumentDataUse only the data part of a document and subscribe to changes
useDocumentMaybeUse a document that might not exist
useDocumentOnceUse a document once and do not subscribe for changes
useDocumentDataOnceUse only the data part of a document once and do not subscribe for changes
useCollectionQuery a collection and subscribe for changes
useCollectionOnceQuery a collection once and do not subscribe for changes

Released under the Apache-2.0 License.