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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

React Context API Typing | TypeScript Mastery lesson | BraveProgrammer
  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 30 of 56

·Typescript

React Context API Typing

20 minutes

Course progress54%

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.
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from TypeScript MasteryBrowse activities
Previous lessonReact Hooks – `useState`, `useEffect` TypesContinue to lesson 31Redux Toolkit + TypeScriptBack to TypeScript Mastery curriculum