Firebase Authentication React Hook

- 83 views

A React Hook to get the logged in user in Firebase Authentication

Please note I’m using the modular version of Firebase. Switch to the relevant imports for versions 8 and below.

import React from "react";
import firebase from "@/lib/firebase"; // The intialized Firebase Client application
import { getAuth, onAuthStateChanged } from "firebase/auth";
 
const useUser = () => {
  const [user, setUser] = React.useState(null);
  const [loadingUser, setLoadingUser] = React.useState(true);
 
  React.useEffect(() => {
    const auth = getAuth(firebase);
 
    // Listen authenticated user
    const unsubscriber = onAuthStateChanged(auth, async (user) => {
      try {
        setLoadingUser(true);
 
        if (user) {
          // User is signed in.
          const { uid, displayName, email, photoURL } = user;
 
          setUser({ uid, displayName, email, photoURL });
        } else {
          setUser(null);
        }
      } catch (error) {
        // Most probably a connection error. Handle appropriately.
      } finally {
        setLoadingUser(false);
      }
    });
 
    // Unsubscribe auth listener on unmount
    return () => unsubscriber();
  }, []);
 
  return { user, loadingUser };
};
 
export default useUser;

Moved the page from under /snippets to /blog on the 10th of February 2024.