Lesson 13 of 20Article16 min
Context API & State Management
Context passes data through the tree without prop drilling. Use for theme, auth user, and locale. For complex global state consider Zustand or Redux Toolkit — but Context is enough for most apps.
Sharing state across screens
Context passes data through the tree without prop drilling. Use for theme, auth user, and locale. For complex global state consider Zustand or Redux Toolkit — but Context is enough for most apps.
AuthContext pattern
type AuthContextType = {
user: User | null;
login: (email: string, pass: string) => Promise<void>;
logout: () => void;
};
const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const login = async (email: string, pass: string) => {
const res = await api.login(email, pass);
setUser(res.user);
await AsyncStorage.setItem("token", res.token);
};
const logout = async () => {
setUser(null);
await AsyncStorage.removeItem("token");
};
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error("useAuth must be inside AuthProvider");
return ctx;
}