Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. TypeScript Mastery

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;
};

Info

Never export the raw context directly; wrap it in a custom hook that performs the undefined check.

Previous: React Hooks – `useState`, `useEffect` TypesNext: Redux Toolkit + TypeScript