useCurrentUser Hook (UseCurrentUser.ts)¶
A custom React hook that provides access to the currently authenticated user's data.
Overview¶
UseCurrentUser.ts implements a hook for accessing and managing the current user's session and profile information.
Usage¶
import { useCurrentUser } from '@/hooks/UseCurrentUser';
function MyComponent() {
const { user, isLoading, error } = useCurrentUser();
// Implementation
}
Return Value¶
{
user: {
id: string;
email: string;
name: string;
image?: string;
role: 'user' | 'admin';
} | null;
isLoading: boolean;
error: Error | null;
}
Features¶
- Automatic session management
- Real-time user updates
- Error handling
- Loading states
- Type safety
Dependencies¶
- React Query for data fetching
- NextAuth.js for session
- TypeScript for types
Implementation Details¶
import { useQuery } from '@tanstack/react-query';
export function useCurrentUser() {
return useQuery(['user'], fetchCurrentUser);
}
Related Hooks¶
useSessionfrom NextAuth.jsuseProfileStatsfor user statistics
Examples¶
Basic Usage¶
function Profile() {
const { user, isLoading } = useCurrentUser();
if (isLoading) return <Loading />;
return <div>Welcome, {user?.name}</div>;
}
With Error Handling¶
function SecureComponent() {
const { user, error } = useCurrentUser();
if (error) return <ErrorMessage error={error} />;
if (!user) return <LoginPrompt />;
return <ProtectedContent user={user} />;
}
Notes¶
- Implements caching
- Handles token refresh
- Provides TypeScript types
- Supports SSR
- Manages stale data