React ⚛️ + Firebase 🔥 without useEffect
Benny Carlsson
Posted on November 17, 2023
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
andfirebaseStore.ts
Lets get to the code!! 🤓
Initialise firebase according to their docs in firebase.ts
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's put it in a custom hook useFirestore.ts
Lastly, lets use it in our react component App.tsx
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! 🎉
Posted on November 17, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 18, 2024