useAuth
The useAuth hook provides access to the current authentication state including the user object and loading status.
Basic Usage
import { useAuth } from 'authsafe-react';
function UserProfile() {
const { user, isAuthenticated, isLoading } = useAuth();
if (isLoading) return <div>Loading...</div>;
if (!isAuthenticated) return <div>Please log in</div>;
return (
<div>
<h2>Welcome, {user?.name}!</h2>
<p>Email: {user?.email}</p>
</div>
);
}Return Values
| Property | Type | Description |
|---|---|---|
user | User | null | Current user object (null if not authenticated) |
isAuthenticated | boolean | Whether the user is currently authenticated |
isLoading | boolean | Whether authentication state is being loaded |
error | Error | null | Authentication error if any |
User Object Properties
| Property | Type | Description |
|---|---|---|
sub | string | Unique user identifier |
name | string | User's display name |
email | string | User's email address |
picture | string | undefined | URL to user's profile picture |
email_verified | boolean | undefined | Whether email has been verified |
Protecting Routes
Use the hook to conditionally render content based on authentication status:
import { useAuth } from 'authsafe-react';
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ children }) {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) return <div>Loading...</div>;
if (!isAuthenticated) return <Navigate to="/login" />;
return children;
}Type Definitions
export interface User {
sub: string;
name?: string;
email?: string;
picture?: string;
email_verified?: boolean;
[key: string]: any;
}
export interface IUseAuth {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
error: Error | null;
}