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.
useContext in a Custom HookCalling 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>;
}
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.
useContext MistakesuseContext(AuthContext.Provider): Pass the Context object itself (AuthContext) to useContext, not .Provider or .Consumer.useContext for multiple contexts?Yes. A single component can call useContext(ThemeContext) and useContext(AuthContext) side by side.
Render another <ThemeContext value="dark"> inside the tree; nested children always read from the closest Provider above them.
useContext returns the default value originally passed to createContext(defaultValue).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.