How do you use Firestore with React?

Answer

The recommended approach for Firestore in React uses the reactfire library or custom hooks. Custom hook pattern: function useDocument(path) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const unsub = onSnapshot(doc(db, ...path.split("/")), snap => { setData(snap.data()); setLoading(false); }); return unsub; }, [path]); return { data, loading }; }. Usage: const { data: user, loading } = useDocument("users/alice"). With reactfire library: const userRef = doc(getFirestore(), "users", "alice"); const { status, data } = useFirestoreDocData(userRef). With SWR or React Query: wrap Firestore fetches in query functions for caching, revalidation, and loading states. Key patterns: (1) Always unsubscribe real-time listeners in useEffect cleanup; (2) Avoid excessive listeners — one listener per required data source; (3) Memoize referencesdoc(db, ...) creates new objects on each render; memoize with useMemo to prevent infinite re-renders; (4) Use the Firebase Emulator for local development.