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;
}What the code does
Count the functions authReducer, AuthProvider and useAuth as the entire surface area of React JWT Auth with Context API.
From react it pulls createContext, useContext, useReducer, type ReactNode — the imports name exactly which library surface the snippet touches. When the guard condition holds, Error is thrown rather than a bogus value returned.
The result comes back as an object carrying null.
Points of care
- Dependency check:
react— not built-in, must be present in the project. - The guard
!ctxshort-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The primary signature is export function AuthProvider({ children }: { children: ReactNode })
Callers only need AuthProvider — everything else stays internal.
The call returns null.
Statements that matter
return <AuthContext.Provider value={{ state, dispatch }}>{children}</AuthContext.Provider>;
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
case 'LOGOUT': return { token: null, user: null };
Interactive Tools for This Topic
FAQ
- Does `AuthProvider` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- How does the code behave when input is bad?
- The code refuses to continue: `Error` is thrown while the state is still recoverable.
- Are there third-party dependencies?
- `react` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.