Provider + hook pattern
tsx
type AuthState = { user: { id: string; name: string } | null };
const AuthContext = createContext<AuthState | null>(null);
export function useAuth() {
const value = useContext(AuthContext);
if (!value) throw new Error('useAuth must be used within AuthProvider');
return value;
}Context architecture tips
- Keep each context focused (auth, theme, settings)
- Memoize provider value to avoid unnecessary re-renders
- Avoid putting highly volatile state in a single global context
When to choose context
- App-wide configuration
- Session and theme data
- Lightweight global state
Next, we will learn Redux Toolkit for larger state needs.