DEV Community

Antoine for Itself Tools

Posted on

Seamlessly Fetch Data in Real-Time with Firebase and React Hooks

At itselftools.com, we have gathered a wealth of knowledge from developing over 30 web applications using technologies like Next.js and Firebase. Throughout our journey, we've refined techniques that enhance the efficiency and scalability of apps. Today, I want to share with you a lightweight and effective method for fetching real-time data using Firebase Firestore in a React application through custom React Hooks.

Crucial Code Explanation

import { useEffect, useState } from 'react';
import { getFirestore, collection, onSnapshot } from 'firebase/firewheel';

const useCollection = (collectionName) => {
  const [documents, setDocuments] = useState([]);
  const db = getFirestore();

  useEffect(() => {
    const unsubscribe = onSnapshot(collection(db, collectionName), (snapshot) => {
      const docs = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
      setDocuments(docs);
    });
    return () => unsubscribe();
  }, [collectionName]);

  return documents;
};

export default useCollection;
Enter fullscreen mode Exit fullscreen mode

Breakdown of the Code

  1. useState Hook - We start by defining a state variable 'documents' which will hold our data array.

  2. getFirestore - This initializes a Firestore instance connected to our Firebase project.

  3. useEffect Hook - This React Hook is crucial for managing side effects. Here, it's tailored to listen to a specific Firestore collection. Upon any data updates, the provided callback fires, updating our 'documents' state accordingly.

  4. onSnapshot Listener - A real-time listener setup on the specified Firestore collection. It fetches all documents and updates state whenever there is a change in the collection data.

  5. Cleaning up on unmount - The return function from useEffect handles the cleanup, unsubscribing from the Firestore collection when the component unmounts to avoid memory leaks.

Real-World Application

Integrating this hook into your React app allows for effortless real-time data updates, enabling features such as live dashboards, instant messaging, or any dynamic content that requires data to be in constant sync with the backend.

Conclusion

Utilizing Firebase Firestore with React can significantly streamline how you manage real-time data. To see our code in action, check out how we've used it in our applications such as finding a professional voice recorder, performing an online camera test, or capturing videos quickly with an instant video recorder. These tools showcase the practical application and robustness of integrating Firebase Firestore efficiently in web apps.

Top comments (0)