DEV Community

Benny Carlsson
Benny Carlsson

Posted on

6 1 2

React ⚛️ + Firebase 🔥 without useEffect

How to initialise Firebase in ReactJS using the useSyncExernalStore() hook instead of useEffect()

After reading You Might Not Need an Effect I wanted to connect my new shiny React app with Firestore without doing it the way I usually do. That is, using the useEffect hook.

useSyncExternalStore to the rescue! I'm not going into details of how to set up your create-react-app or how to setup Firestore. In short, here it is:

  • Setup react with npx create-react-app

  • npm install firebase

  • Setup firebase in firebase dev console

  • Create 3 files: db/firebase.ts, hooks/useFireStore.ts and firebaseStore.ts

Lets get to the code!! 🤓

Initialise firebase according to their docs in firebase.ts

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: FIREBASE_API_KEY,
authDomain: FIREBASE_AUTHDOMAIN,
projectId: FIREBASE_PROJECT_ID,
storageBucket: FIREBASE_STORAGE_BUCKET,
messagingSenderId: FIREBASE_MESSAGING_SENDER_ID,
appId: VITE_FIREBASE_APP_ID,
measurementId: VITE_FIREBASE_MEASUREMENT_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
view raw firebase.ts hosted with ❤ by GitHub

Setup your store in firebaseStore.ts (we don't really have a third party store but instead we rely on firebase and its caching to act as our store).

let data: string | undefined;
const firebaseStore = {
getSnapshot: () => {
return data;
},
subscribe: (callback: () => void) => {
const unsub = onSnapshot(doc(db, "my-collection", "my-document"), (doc) => {
data = doc.data()?.test;
callback();
});
return () => {
data = undefined;
unsub();
};
},
};
export default firebaseStore

Let's put it in a custom hook useFirestore.ts

const useFirestore = () => {
const data = useSyncExternalStore(firebaseStore.subscribe, firebaseStore.getSnapshot);
return data;
};
view raw useFirestore.ts hosted with ❤ by GitHub

Lastly, lets use it in our react component App.tsx

function App() {
const data = useFirestore();
return <h1>{data}</h1>;
}
view raw App.tsx hosted with ❤ by GitHub

Now whenever Firestore updates the listener will be triggered in firebaseStore.ts and update the data in our custom hook and our component will rerender with the new data. Tadaaa! 🎉

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (5)

Collapse
 
codewithshahan profile image
Programming with Shahan

Great article. Keep pushing new articles. Thank You.

Collapse
 
hugaidas profile image
Victoria

Very nice! I think this react hook is really underrated, I am very glad to see education content about it!

Collapse
 
bennycarlsson profile image
Benny Carlsson

Thanks! Indeed, I was surprised how hard it was to find more content about this hook outside of the official docs.

Collapse
 
hugaidas profile image
Victoria

You might like this video by Jack Herrington, he also mentioned this hook in combination with react context, could server as an inspiration for your next article :)

Collapse
 
glntn101 profile image
Luke

Great, thank you!

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay