useAuth hook provides access to the authentication context, including the current user, session state, and sign-out functionality.
Import
Usage
Return value
The hook returns an object with the following properties:The currently authenticated user object, or
null if not authenticated.Indicates whether the authentication state is being loaded. Set to
true during initial session check or sign-in process.Async function to sign out the current user. Returns an object with an
error property if the sign-out fails.Contains any authentication error that occurred, or
null if no error.Function to clear the current error state.
Error handling
The hook will throw an error if used outside of anAuthProvider:
AuthProvider:
App.tsx
Implementation details
The hook internally uses React’suseContext to access the AuthContext. The context is managed by AuthProvider, which:
- Monitors Supabase authentication state changes
- Fetches extended user information from the
tcUsuariostable - Caches user data to minimize database queries
- Handles token refresh without blocking the UI
- Automatically clears cache on sign-out
Token refresh behavior
When a token refresh occurs (TOKEN_REFRESHED event), the hook updates the session without blocking the UI or re-querying the database. This ensures a smooth user experience without unnecessary loading states.
Initial session loading
On initial page load (INITIAL_SESSION event), the hook loads the user with default values first, then fetches real data in the background to prevent blocking the UI.
Type definitions
~/workspace/source/src/contexts/AuthContext.tsx
Related
- AuthContext - The underlying context provider
- Supabase Auth - Authentication service documentation