0
0
FirebaseHow-ToBeginner · 4 min read

How to Use Firestore with React: Simple Guide

To use Firestore with React, first install Firebase SDK and initialize Firestore in your app. Then use React hooks like useEffect and useState to fetch and display data from Firestore collections or documents.
📐

Syntax

Here is the basic syntax to connect Firestore with React:

  • Import Firebase and Firestore modules.
  • Initialize Firebase app with your config.
  • Create a Firestore instance.
  • Use React hooks to read/write data.
javascript
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore';
import React, { useEffect, useState } from 'react';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

function MyComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const querySnapshot = await getDocs(collection(db, 'myCollection'));
      const items = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
      setData(items);
    }
    fetchData();
  }, []);

  return (
    <div>
      {data.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
}
💻

Example

This example shows a React component that fetches and displays a list of items from a Firestore collection called products. It uses Firebase SDK v9 modular syntax and React hooks.

javascript
import React, { useEffect, useState } from 'react';
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore';

const firebaseConfig = {
  apiKey: 'AIzaSyExampleKey',
  authDomain: 'your-app.firebaseapp.com',
  projectId: 'your-app',
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

function ProductList() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    async function loadProducts() {
      const querySnapshot = await getDocs(collection(db, 'products'));
      const productList = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
      setProducts(productList);
    }
    loadProducts();
  }, []);

  return (
    <div>
      <h2>Product List</h2>
      <ul>
        {products.map(product => (
          <li key={product.id}>{product.name} - ${product.price}</li>
        ))}
      </ul>
    </div>
  );
}

export default ProductList;
Output
<div> <h2>Product List</h2> <ul> <li>Apple - $1</li> <li>Banana - $0.5</li> <li>Orange - $0.8</li> </ul> </div>
⚠️

Common Pitfalls

Common mistakes when using Firestore with React include:

  • Not initializing Firebase app before using Firestore.
  • Forgetting to use async/await when fetching data, causing empty results.
  • Not cleaning up listeners if using real-time updates.
  • Using deprecated Firebase SDK syntax instead of modular v9+ syntax.
javascript
/* Wrong: Using older Firebase syntax and no async/await */
import firebase from 'firebase/app';
import 'firebase/firestore';

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

function MyComponent() {
  const [data, setData] = React.useState([]);

  React.useEffect(() => {
    async function fetchData() {
      const snapshot = await db.collection('items').get();
      setData(snapshot.docs.map(doc => doc.data()));
    }
    fetchData();
  }, []);

  return <div>{data.length}</div>;
}

/* Right: Using modular syntax and async/await */
import { getFirestore, collection, getDocs } from 'firebase/firestore';

const db = getFirestore();

React.useEffect(() => {
  async function fetchData() {
    const snapshot = await getDocs(collection(db, 'items'));
    setData(snapshot.docs.map(doc => doc.data()));
  }
  fetchData();
}, []);
📊

Quick Reference

Here is a quick summary of key Firestore with React steps:

  • Install Firebase: npm install firebase
  • Initialize Firebase app with your config.
  • Get Firestore instance: const db = getFirestore(app);
  • Read data with getDocs(collection(db, 'yourCollection')).
  • Use React useEffect and useState to manage data fetching and display.

Key Takeaways

Initialize Firebase app before using Firestore in React.
Use Firebase SDK v9 modular syntax with async/await for data fetching.
Use React hooks like useEffect and useState to handle Firestore data.
Avoid deprecated Firebase syntax to prevent errors.
Clean up listeners if using real-time Firestore updates.