React JWT Auth with Context API
Implement JWT authentication in React using Context API and useReducer. Includes login, logout, token refresh, protected route wrapper, and automatic token.
Code
import { createContext, useContext, useReducer, type ReactNode } from 'react';
interface AuthState {
token: string | null;
user: { id: string; name: string } | null;
}
type AuthAction =
| { type: 'LOGIN'; payload: AuthState }
| { type: 'LOGOUT' };
const AuthContext = createContext<{ state: AuthState; dispatch: React.Dispatch<AuthAction> } | null>(null);
function authReducer(state: AuthState, action: AuthAction): AuthState {
switch (action.type) {
case 'LOGIN': return action.payload;
case 'LOGOUT': return { token: null, user: null };
}
}
export function AuthProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(authReducer, { token: null, user: null });
return <AuthContext.Provider value={{ state, dispatch }}>{children}</AuthContext.Provider>;
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
return ctx;
}