Lesson

useContext

10 min reading
Free Course

React useContext Hook: Consuming Shared State Anywhere

useContext reads the current value of a React Context created with createContext and automatically subscribes your component to updates from the nearest matching Provider above it. It replaces verbose Consumer render-props and eliminates multi-level prop drilling across headers, sidebars, and nested forms.

Wrapping useContext in a Custom Hook

Calling useContext(AuthContext) directly in dozens of files scatters context imports everywhere. Wrapping it inside a dedicated useAuth() helper centralizes error checking and makes missing providers fail loudly during development.

import { createContext, useContext, useState } from 'react';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState({ name: 'Samira', role: 'editor' });
  const signOut = () => setUser(null);

  return (
    <AuthContext value={{ user, signOut }}>
      {children}
    </AuthContext>
  );
}

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) {
    throw new Error('useAuth must be called inside <AuthProvider>');
  }
  return ctx;
}

export function ProfileMenu() {
  const { user, signOut } = useAuth();
  if (!user) return <span>Signed out</span>;
  return <button type="button" onClick={signOut}>Sign out ({user.name})</button>;
}

How Updates Propagate to Consumers

Whenever the Provider's value prop changes (checked by Object.is), React schedules a re-render for every component calling useContext on that context—even if intermediate parent components are wrapped in React.memo. Memoizing the context value object with useMemo keeps consumer renders predictable and avoids unnecessary DOM work across large sidebars or forms.

Common useContext Mistakes

  • Calling useContext(AuthContext.Provider): Pass the Context object itself (AuthContext) to useContext, not .Provider or .Consumer.
  • Creating One Giant Monolithic Context: Putting user auth, notifications, and modal state inside one Context forces unrelated components to re-render on every small change. Split independent concerns into separate contexts.

Frequently Asked Questions

Can a component call useContext for multiple contexts?

Yes. A single component can call useContext(ThemeContext) and useContext(AuthContext) side by side.

How can a child component override a Context value for its own subtree?

Render another <ThemeContext value="dark"> inside the tree; nested children always read from the closest Provider above them.

What happens if no Provider wraps the component?

useContext returns the default value originally passed to createContext(defaultValue).

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol
Lesson Recap Quiz Available

Test Your Knowledge

You've completed this section! Take a quick 5-question quiz to check your understanding.

React Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum