reactjsgoogle-cloud-firestorereact-hooksswr

Differences between useEffect() and useSWRSubscription()


I am reading some data real-time from Firebase's Cloud Firestore using a query and useEffect:

import { useEffect } from 'react'

useEffect(() => {
    const q = query(
        collection('some collection'),
        where('some condition')
    )

    const unsubscribe = onSnapshot(q, qs => {
        const datas = [];
        qs.forEach((doc) => {
            datas.push(doc.data());
        });
        console.log(datas);
    })
    return () => unsubscribe && unsubscribe()
})

I have recently found out this SWR, described as a React Hook for Data Fetching.

In their documentation, they show this example where they are using useSWRSubscription to subscribe to a Firestore data source. So I can recreate the previous code block like this:

import useSWRSubscription from 'swr/subscription'
 
const { datas } = useSWRSubscription(queryParams ? queryParams : null, (_, { next }) => {
    const q = query(
        collection('some collection'),
        where('some condition')
    )

    const unsubscribe = onSnapshot(q,
        qs => {
            next(
                null,
                qs.docs.map(doc => doc.data())
            )
        },
        err => {
            return next(err)
        }
    )
    return () => unsubscribe && unsubscribe()
}

console.log(datas)

Is there any difference between these two code blocks?


Solution

  • Yes, the behaviour differs. Because useEffect called without deps array so its callback will be executed on any render along with destructor. So any component re-render will connect to socket and disconnect immidiatelly. Otherwise use SW Subscription will work as expected and will disconnect on socket error event.