DEV Community

Benny Carlsson
Benny Carlsson

Posted on

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

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! 🎉

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!