Are you doing a React or Next.js application and do you want to implement Google Firebase authentication? This article is totally for you.
I will show you how to manage authentication (in my case with Github, but is pretty the same with other methods), and all with a single custom React Hook.
Obviously, we need to set up the firebase library in our app before doing the authentication, so I will paste here some example code in order to go faster.
In the previous code snippet we have initialized the firebase app and also imported the auth module always from firebase.
Now we can start doing authentication code, I will focus mainly on the Hook code, and not on the UI, but I will show you an example of how to use it in the UI also.
This is our Hook:
As you can see is pretty simple, we have imported the firebase library from the previous snippet and wrote the signIn and signOut function for the authentication management.
As I mentioned before, this case is with the GitHub login, but firebase supports a lot of different providers, you only need to change the provider in the signIn function.
Particular attention must be paid to the useEffect hook. With it, every time the hook is called, it will check if the user exists or not and will pass the user to the handleUser function, which updates the state with the current firebase user instance, or with null in case the user was not logged in.
This is all the code you need for managing the authentication.
Using in the UI
In order to use the just created hook, we can do something like this:
This is a simple Next.js page, as you can see is pretty simple.
Thank you for reading this article, I really appreciate it.
If you want you can follow me on Twitter