Lesson 30 of 56 · Typescript
React Context API Typing
Duration: 20 minutes
Creating a Typed Context
interface AuthContext {
user: { id: string; name: string } | null;
login(name: string): void;
logout(): void;
}
const AuthCtx = React.createContext<AuthContext | undefined>(undefined);
Provider Component
export const AuthProvider: React.FC = ({ children }) => {
const [user, setUser] = useState<AuthContext["user"]>(null);
const login = (name: string) => setUser({ id: Date.now().toString(), name });
const logout = () => setUser(null);
return (
<AuthCtx.Provider value={{ user, login, logout }}>
{children}
</AuthCtx.Provider>
);
};
Consuming the Context
const useAuth = () => {
const ctx = React.useContext(AuthCtx);
if (!ctx) throw new Error('AuthProvider missing');
return ctx;
};