This code defines an authentication context for a React application...

June 29, 2025 at 01:20 AM

import React, { createContext, useContext, useState, useEffect } from 'react'; import { supabase } from '../supabase/client'; const AuthContext = createContext(); export const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const { data } = supabase.auth.onAuthStateChange( async (event, session) => { setUser(session?.user || null); setLoading(false); } ); return () => { data.subscription.unsubscribe(); }; }, []); const signUp = async (email, password) => { setLoading(true); const { user, session, error } = await supabase.auth.signUp({ email, password, options: { emailRedirectTo: null, }, }); setLoading(false); if (error) throw error; setUser(user); return { user, session }; }; const login = async (email, password) => { setLoading(true); const { user, session, error } = await supabase.auth.signInWithPassword({ email, password, }); setLoading(false); if (error) throw error; setUser(user); return { user, session }; }; const logout = async () => { setLoading(true); const { error } = await supabase.auth.signOut(); setLoading(false); if (error) throw error; setUser(null); }; return ( <AuthContext.Provider value={{ user, loading, signUp, login, logout }}> {children} </AuthContext.Provider> ); }; export const useAuth = () => { return useContext(AuthContext); };

This code defines an authentication context for a React application using Supabase. Here's what it does step-by-step:

  1. Imports:

    • Various React functions (createContext, useContext, useState, useEffect) are imported for creating context, managing state, and handling lifecycle effects.
    • supabase is imported as a Supabase client for handling authentication.
  2. Creating Context:

    • AuthContext is created using createContext() to store authentication-related state and functions.
    • AuthProvider is a context provider which wraps parts of the app that require authentication access.
  3. State Management:

    • Two states are maintained:
      • user: The current authenticated user, initially set to null.
      • loading: A flag to track whether authentication requests are in progress, initially set to true.
  4. Effect for Authentication State Changes:

    • A useEffect hook is used to listen for authentication state updates using supabase.auth.onAuthStateChange.
    • Whenever there is a change to the authentication state (login, logout, signup, etc.), the user is set (using setUser), or cleared if there is no authenticated session.
    • When the component unmounts, it cleans up the subscription to avoid memory leaks.
  5. Signup Functionality (signUp):

    • signUp handles user registration using supabase.auth.signUp.
    • It accepts email and password as arguments, sets the loading state, and makes the API call.
    • The new user and session are returned, or an error is thrown if the signup fails.
  6. Login Functionality (login):

    • login handles user login using supabase.auth.signInWithPassword.
    • It accepts email and password as arguments, sets loading, and makes the API call to log in.
    • It updates the user state upon success or throws an error if authentication fails.
  7. Logout Functionality (logout):

    • logout handles signing the user out using supabase.auth.signOut.
    • It sets the loading state, clears the user state, and throws an error if the logout fails.
  8. Providing Context Values:

    • Through the AuthContext.Provider, the context provides values and functions globally:
      • user (current authenticated user),
      • loading (loading state),
      • signUp, login, and logout functions for authentication actions.
    • This makes these accessible to components wrapped with the AuthProvider.
  9. Hook for Accessing Context (useAuth):

    • A helper function, useAuth, wraps useContext(AuthContext) to provide easier access to the context values in child components.

Usage:

  • Wrap your app's root or specific parts with the AuthProvider component to enable authentication functionalities there.
  • Use the useAuth() hook in child components to access the user, signUp, login, and logout features as well as the loading state.

This implementation serves as an authentication provider for managing user session states (signup, login, logout, and subscription to session changes) using Supabase within a React app.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node