useAuth Hook
TheuseAuth hook provides complete authentication functionality including login, registration, logout, and onboarding management. It integrates with Redux for global state management.
Import
Basic Usage
Return Value
The hook returns an object containing all auth state and functions:Authentication State (from Redux)
The currently authenticated user object, or
null if not logged in.JWT authentication token for API requests.
true if user is logged in, false otherwise.true during login/register operations.Error message from failed authentication attempts, or
null if no error.true if user is newly registered and needs to complete onboarding.Form State
Current email input value (default: ‘[email protected]’ for demo).
Function to update email state.
Current password input value (default: ‘123456’ for demo).
Function to update password state.
Authentication Functions
Attempts to log in with current email and password.Parameters:
e(optional) - Form event to prevent default submission
true if login successful, false otherwise.Behavior:- Sets loading state
- Validates credentials against mock user database
- Dispatches Redux actions for success/failure
- Simulates network latency (1.5s)
Registers a new user as system owner.Parameters:
nombreNuevo- Full name of new useremailNuevo- Email address for new accountpasswordNuevo(optional) - Password for new account
true if registration successful, false otherwise.Behavior:- Checks if email already exists
- Creates new user with OWNER role
- Sets
isNew: trueto trigger onboarding - Automatically logs in the new user
Logs out the current user and clears authentication state.
Marks the onboarding process as complete for new users.
Examples
Complete Login Flow
Registration Flow
Protected Route with Auth Check
User Profile Display
Onboarding Flow
User Roles
Mock Users (Development)
The hook uses a mock user database for development:Redux Integration
The hook dispatches these Redux actions:loginStart()- Sets loading stateloginSuccess({ user, token, isNew })- Stores authenticated userloginFailure(errorMessage)- Stores error messagelogout()- Clears auth statecompleteOnboarding()- Marks onboarding complete
Error Messages
Possible error messages:- “Credenciales incorrectas. Verifica tu correo o contraseña.” - Invalid credentials
- “Ocurrió un error interno al intentar iniciar sesión.” - Server error during login
- “Este correo ya está registrado en el sistema.” - Email already exists during registration
- “Error en el registro del sistema.” - Server error during registration
State Management Flow
The hook includes default credentials ([email protected] / 123456) for quick prototyping. Remove these in production.
Source Code
Location:/home/daytona/workspace/source/src/hooks/useAuth.ts:1