Back to SDK Reference
React Hooks
Seamless React integration with EasyAuth hooks
useAuth()
Provides authentication state and user information
useAuth(): { user, isAuthenticated, ... }
useSession()
Manages session state and updates
useSession(): { data, status, update }
useAuth()
The useAuth
hook provides the authentication state including whether the user is authenticated, loading status, and user details.
Basic Usage
import { useAuth } from 'easyauth';
function Dashboard() {
const { user, isAuthenticated, isLoading } = useAuth();
if (isLoading) return <div>Loading...</div>;
return (
<div>
{isAuthenticated ? (
<div>
<h1>Welcome, {user.username}!</h1>
<p>Email: {user.email}</p>
</div>
) : (
<p>Please log in.</p>
)}
</div>
);
}
Advanced Usage
import { useAuth } from 'easyauth';
function UserProfile() {
const { user, isAuthenticated, isLoading, isUnauthenticated } = useAuth();
// Show loading state
if (isLoading) {
return <div className="spinner">Loading...</div>;
}
// Handle unauthenticated state
if (isUnauthenticated) {
return <div>Please sign in to continue.</div>;
}
// User is authenticated, show profile
return (
<div>
<h1>User Profile</h1>
<p>ID: {user.id}</p>
<p>Email: {user.email}</p>
<p>Username: {user.username}</p>
<p>Role: {user.role}</p>
</div>
);
}
useSession()
The useSession
hook provides access to the session data and status. It automatically keeps track of session state and updates.
Usage
import { useSession } from 'easyauth';
function UserStatus() {
const { data: session, status, update } = useSession();
if (status === 'loading') return <div>Loading session...</div>;
return (
<div>
{status === 'authenticated' ? (
<div>
<h1>User: {session.user.username}</h1>
<p>Status: Logged In</p>
<button onClick={update}>Refresh Session</button>
</div>
) : (
<p>Status: Not authenticated.</p>
)}
</div>
);
}
Status Types
'loading'
Session is being fetched'authenticated'
User is logged in'unauthenticated'
User is not logged inHook Return Values
useAuth() Returns
Property | Type | Description |
---|---|---|
user | User | null | Current user object or null |
isAuthenticated | boolean | True if user is authenticated |
isLoading | boolean | True if session is loading |
isUnauthenticated | boolean | True if user is not authenticated |
useSession() Returns
Property | Type | Description |
---|---|---|
data | Session | null | Current session data |
status | string | Session status ('loading', 'authenticated', 'unauthenticated') |
update | function | Function to manually refresh session |
Next Steps
Now that you understand React hooks available in EasyAuth, continue exploring our SDK: