Course contentsShow
← React
Lesson 812 of 2,39621. Context FundamentalsFree lesson

Current User and Auth State in Context

Learn how authentication state benefits from context since many components need user info.

Current User and Auth State in Context

You'll learn why authentication state is one of the most common and practical uses of React Context.

The Authentication Information Problem

Authentication state—who's logged in, their username, permissions, profile picture—is needed everywhere in your app. Your navbar needs it to show a profile button. Your sidebar needs it to display personalized content. Protected routes need it to decide access. Settings pages need it to show user details.

Without Context, you'd pass currentUser through dozens of components that don't care about it themselves—they just relay it downward. This is textbook prop drilling.

Why Auth Belongs in Context

Authentication is genuinely global state. When a user logs in or out, many unrelated parts of your UI need to react simultaneously. The user doesn't "belong" to one component—it's application-wide information.

Think of auth state like the weather: every window in a building shows the same sky outside. You don't need to tell each room individually what the weather is—they all look at the same shared reality.

Common auth context values:

  • currentUser object (or null if logged out)
  • isAuthenticated boolean
  • login() and logout() functions
  • loading state during auth checks

Any component can call useAuth() (your custom hook) to access this information without receiving it as props.

The Pattern in Practice

You create an AuthContext, wrap your app in <AuthProvider>, and store the user object there. Components like <UserMenu>, <Dashboard>, and <ProtectedRoute> all read from the same context. When logout happens, the context updates once, and every consumer re-renders with null for the user.

Key Takeaway: Authentication state is a perfect Context candidate because it's truly global, needed by many unrelated components, and changes infrequently but must propagate everywhere when it does.