TS
IntermediateReact Hooks

React Custom Hook for Firebase Auth

A reusable custom hook that manages Firebase authentication state with loading states and error handling.

ReactFirebaseTypeScriptAuthenticationCustom Hooks
TypeScript
60 lines
import { useState, useEffect, useCallback, useMemo } from 'react';
import { User, onAuthStateChanged, signOut } from 'firebase/auth';
import { auth } from '../lib/firebase';

interface AuthState {
  user: User | null;
  loading: boolean;
  error: string | null;
}

export function useAuth() {
  const [authState, setAuthState] = useState<AuthState>({
    user: null,
    loading: true,
    error: null
  });

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(
      auth,
      (user) => {
        setAuthState({
          user,
          loading: false,
          error: null
        });
      },
      (error) => {
        setAuthState({
          user: null,
          loading: false,
          error: error.message
        });
      }
    );

    return unsubscribe;
  }, []);

  const logout = useCallback(async () => {
    try {
      setAuthState(prev => ({ ...prev, loading: true }));
      await signOut(auth);
    } catch (error) {
      setAuthState(prev => ({
        ...prev,
        loading: false,
        error: error instanceof Error ? error.message : 'Logout failed'
      }));
    }
  }, []);

  const value = useMemo(() => ({
    ...authState,
    logout,
    isAuthenticated: !!authState.user
  }), [authState, logout]);

  return value;
}

Performance

Optimized with useCallback and useMemo to prevent unnecessary re-renders

Best Practices

  • Uses TypeScript for type safety
  • Implements proper cleanup with useEffect
  • Handles loading and error states
  • Memoizes expensive operations
February 15, 2024
GitHub