Auth Hook Join Firestore data to the current user with a custom react hook

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.
SignUp for Unlimited PRO Access

OR


*Enrollment provides full access to this course (and updates) for life.

Custom User Data Hook

Use this hook to read the current Firebase User, then use the uid to fetch the public profile document from Firestore.

file_type_js_official lib/hooks.js
import { auth, firestore } from '../lib/firebase';
import { useEffect, useState } from 'react';
import { useAuthState } from 'react-firebase-hooks/auth';

// Custom hook to read  auth record and user profile doc
export function useUserData() {
  const [user] = useAuthState(auth);
  const [username, setUsername] = useState(null);

  useEffect(() => {
    // turn off realtime subscription
    let unsubscribe;

    if (user) {
      const ref = firestore.collection('users').doc(user.uid);
      unsubscribe = ref.onSnapshot((doc) => {
        setUsername(doc.data()?.username);
      });
    } else {
      setUsername(null);
    }

    return unsubscribe;
  }, [user]);

  return { user, username };
}

Usage in the App Component

file_type_js_official pages/_app.js
import { useUserData } from '../lib/hooks';

function MyApp({ Component, pageProps }) {
  
  const userData = useUserData();

  return (
    <UserContext.Provider value={userData}>
      <Navbar />
      <Component {...pageProps} />
      <Toaster />
    </UserContext.Provider>
  );
}

Q&A Chat