useHeader Hook Logic - abhiram-shaji/Langroove GitHub Wiki

Developer Documentation: useHeader Hook

This documentation provides an overview of the useHeader hook, which manages user authentication state and retrieves user information for display in a header or similar component.


Overview

The useHeader hook:

  1. Tracks the current user's authentication state and user ID.
  2. Integrates with the useUserInfo hook to fetch user information based on the user ID.
  3. Manages loading states for both authentication and user information retrieval.

Features and Functionality

1. Tracking User Authentication State

Purpose

  • Listens to changes in Firebase Authentication state to retrieve the current user's ID.

Implementation

  1. Functionality:

    • Uses Firebase Authentication's onAuthStateChanged to monitor login/logout events.
    • Updates the userId state with the logged-in user's UID or null if no user is authenticated.
  2. Code Snippet:

    useEffect(() => {
      const unsubscribe = auth.onAuthStateChanged((currentUser) => {
        if (currentUser) {
          setUserId(currentUser.uid);
        } else {
          setUserId(null);
        }
        setIsUserLoading(false); // Stop loading after user is fetched
      });
    
      return () => unsubscribe();
    }, []);
  3. Process:

    • Sets userId to the UID of the authenticated user or null if unauthenticated.
    • Updates isUserLoading to false after processing.

2. Fetching User Information

Purpose

  • Retrieves detailed user information (e.g., name, email) for display in the header.

Implementation

  1. Functionality:

    • Invokes the useUserInfo hook with the userId to fetch associated user details.
  2. Code Snippet:

    const { userInfo, loading: userInfoLoading } = useUserInfo(userId || '');
  3. Process:

    • Passes the userId to useUserInfo only if it's non-empty.
    • Tracks the loading state and retrieved userInfo provided by useUserInfo.

3. Managing Loading States

Purpose

  • Differentiates between the loading state for authentication and user information retrieval.

Implementation

  1. State Variables:

    • isUserLoading: Tracks whether authentication state is being processed.
    • userInfoLoading: Tracks whether user information is being fetched.
  2. Combined Usage:

    • isUserLoading is set to false once onAuthStateChanged finishes.
    • userInfoLoading reflects the loading state of the useUserInfo hook.

Key Properties and Methods

Property/Method Description
userId The currently authenticated user's UID or null if unauthenticated.
isUserLoading Boolean indicating whether the authentication state is being processed.
userInfo Detailed user information fetched using the useUserInfo hook.
userInfoLoading Boolean indicating whether user information is being fetched.

Usage Example

import React from 'react';
import useHeader from './hooks/useHeader';

const Header = () => {
  const { userId, isUserLoading, userInfo, userInfoLoading } = useHeader();

  if (isUserLoading || userInfoLoading) {
    return <div>Loading...</div>;
  }

  return (
    <header>
      {userId && userInfo ? (
        <div>
          <h1>Welcome, {userInfo.name}</h1>
          <p>Email: {userInfo.email}</p>
        </div>
      ) : (
        <div>
          <h1>Welcome, Guest</h1>
        </div>
      )}
    </header>
  );
};

export default Header;

Error Handling

  • Unauthenticated State:
    • If no user is logged in, userId is set to null, and userInfo is not fetched.
  • Empty User Info:
    • If userInfo is not available, the component can display a fallback message.

Notes

Dependencies

  • Relies on the useUserInfo hook to fetch user details.
  • Requires Firebase Authentication (auth) to monitor authentication state.

Performance

  • Ensures real-time updates on authentication changes using Firebase's listener.
  • Optimized by separating authentication and user info loading states.

For more information, refer to the Firebase Authentication Documentation and React Documentation on Hooks.

⚠️ **GitHub.com Fallback** ⚠️