DEV Community

Krunal Kanojiya
Krunal Kanojiya

Posted on

How To Boost Your Firebase App’s Efficiency with Real-Time Listeners in React.js

Firebase’s onSnapshot method is used to set up real-time listeners for changes to data in a Firebase database. This method takes a reference to a collection or document in your Firebase database as its first argument, and a callback function as its second argument. Whenever the data in the referenced collection or document changes, the callback function is invoked with a snapshot of the updated data.

Here’s an example of how to use onSnapshot **in a **React.js application to display a list of messages stored in a Firebase Firestore database:

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

const db = getFirestore();
const messagesRef = collection(db, 'messages');

function App() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const unsubscribe = onSnapshot(messagesRef, (snapshot) => {
      const updatedMessages = =>;
    return () => unsubscribe();
  }, []);

  return (
        {, index) => (
          <li key={index}>{message.text}</li>

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we first import the necessary Firebase modules (getFirestore, collection, and onSnapshot) and create a reference to the messages collection in the Firestore database.

We then use the useState hook to create a state variable called messages, which we will use to store the messages data retrieved from the database.

We use the useEffect hook to attach a listener to the messages collection in the database using the onSnapshot method. The listener will update the messages state variable whenever the data in the messages collection changes.

Finally, we use the messages state variable to render the list of messages in our React component.

Overall, onSnapshot is a powerful tool for building real-time, responsive, and efficient Firebase applications in React.js.

Top comments (0)